ngram
listlengths 0
67.8k
|
|---|
[
"<<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global constant variables. \"\"\" import",
"# SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global constant variables. \"\"\" import os.path",
"\"\"\" import os.path GLOB_MARKER: str = '*' PATH_SEP: str = os.path.sep # vim:sw=4:ts=4:et:",
"global constant variables. \"\"\" import os.path GLOB_MARKER: str = '*' PATH_SEP: str =",
"2018 - 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global",
"MIT # r\"\"\"ioinfo.constants to provide global constant variables. \"\"\" import os.path GLOB_MARKER: str",
"# # Copyright (C) 2018 - 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT #",
"r\"\"\"ioinfo.constants to provide global constant variables. \"\"\" import os.path GLOB_MARKER: str = '*'",
"SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global constant variables. \"\"\" import os.path GLOB_MARKER:",
"variables. \"\"\" import os.path GLOB_MARKER: str = '*' PATH_SEP: str = os.path.sep #",
"provide global constant variables. \"\"\" import os.path GLOB_MARKER: str = '*' PATH_SEP: str",
"2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global constant variables.",
"# Copyright (C) 2018 - 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants",
"to provide global constant variables. \"\"\" import os.path GLOB_MARKER: str = '*' PATH_SEP:",
"(C) 2018 - 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide",
"<NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global constant variables. \"\"\"",
"- 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to provide global constant",
"constant variables. \"\"\" import os.path GLOB_MARKER: str = '*' PATH_SEP: str = os.path.sep",
"Copyright (C) 2018 - 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # r\"\"\"ioinfo.constants to",
"# r\"\"\"ioinfo.constants to provide global constant variables. \"\"\" import os.path GLOB_MARKER: str ="
] |
[
"default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\")",
"{}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]:",
"utils import ensembel_model def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'):",
"'t', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'):",
"\"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs))",
"default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"]",
"use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version:",
"from get_data import import_data from model_zoo import googLeNet, resnet, load_model import utils import",
"parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu:",
"load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T:",
"parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store',",
"import googLeNet, resnet, load_model import utils import ensembel_model def str2bool(v): if v.lower() in",
"resnet, load_model import utils import ensembel_model def str2bool(v): if v.lower() in ('yes', 'true',",
"parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") #",
"{}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size))",
"action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store',",
"model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model, batch_size=args.batch_size, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred,",
"x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T',",
"# my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # ) #",
"regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu()",
"train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size:",
"default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use",
"print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]:",
"draw_his import train import test from get_data import import_data from model_zoo import googLeNet,",
"test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs,",
"type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]:",
"argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10)",
"type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]:",
"raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store',",
"set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v))",
"batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util",
"import draw_his import train import test from get_data import import_data from model_zoo import",
"= import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size,",
"os import draw_his import train import test from get_data import import_data from model_zoo",
"parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr))",
"regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util",
"my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), #",
"# my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(),",
"my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # ) # new_model",
"new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False,",
"parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args",
"test from get_data import import_data from model_zoo import googLeNet, resnet, load_model import utils",
"print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]:",
"parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir',",
"# cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet new_model",
"T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() #",
") # new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v,",
"import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize,",
"os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x:",
"False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\")",
"action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store',",
"new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True",
"ensembel_model def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True",
"parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v',",
"new_model = resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True )",
"parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int,",
"argparse import os import draw_his import train import test from get_data import import_data",
"if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in",
"{}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util =",
"{}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils( #",
"('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f',",
"v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value",
"T=args.T, # alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model,",
"{}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util",
"resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set,",
"= load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset(",
"default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\"",
"model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model, batch_size=args.batch_size, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, just_weights=False )",
"action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir",
"\"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x:",
") train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set,",
"= parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate:",
"print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils()",
"args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning",
"= os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda",
"print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]:",
"= utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # ) # new_model =",
"parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10)",
"{}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha))",
"rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain:",
"action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False)",
"= resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set,",
"show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model, batch_size=args.batch_size, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval,",
"'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n',",
"print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version:",
"default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store',",
"'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser =",
"expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs',",
"batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model =",
"googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True",
"import import_data from model_zoo import googLeNet, resnet, load_model import utils import ensembel_model def",
"else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr',",
"test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred,",
"import utils import ensembel_model def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y',",
"in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')",
"{}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize))",
"= utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T,",
"{}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain))",
"epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize:",
"default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float,",
"'0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store',",
"'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu',",
"type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str,",
"valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v,",
"type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),",
"retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha:",
"print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util =",
"model_zoo import googLeNet, resnet, load_model import utils import ensembel_model def str2bool(v): if v.lower()",
"print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]:",
"googLeNet, resnet, load_model import utils import ensembel_model def str2bool(v): if v.lower() in ('yes',",
"retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train(",
"'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return",
"type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str,",
"model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set",
"gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v))",
"default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1)",
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]:",
"alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new =",
"print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]:",
"value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001)",
"utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet",
"load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v,",
"x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store',",
"return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else:",
"train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule )",
"train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train,",
"load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir,",
"\"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)),",
"elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean",
"'1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False",
"create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set =",
"parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v',",
"type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args()",
"parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)),",
"# default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False)",
"get_data import import_data from model_zoo import googLeNet, resnet, load_model import utils import ensembel_model",
"my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha",
"utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # )",
"= googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain,",
"bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store',",
"train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model)",
"type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str,",
"lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False)",
"epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model",
"default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize',",
"model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule",
"= \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda",
"type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32)",
"default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set",
") train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval,",
"draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model, batch_size=args.batch_size, get_true_pred=my_util.get_true_pred,",
"parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] =",
"from model_zoo import googLeNet, resnet, load_model import utils import ensembel_model def str2bool(v): if",
"# alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new",
") draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model, batch_size=args.batch_size,",
"just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True )",
"action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir =",
"utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, #",
"eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v,",
"bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float,",
"argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float,",
"type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size', action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha',",
"learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model,",
"= \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"])) print(\"[info]: set learning rate: {}\".format(args.lr)) print(\"[info]: epochs:",
"= model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set, new_model=new_model, batch_size=args.batch_size, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, just_weights=False",
"import argparse import os import draw_his import train import test from get_data import",
"action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu)",
"type=str, default=default_load_data_dir) parser.add_argument('--retrain', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--regularize', type=lambda x: bool(str2bool(x)), default=False) parser.add_argument('--batch_size',",
"action='store', type=float, default=0.1) args = parser.parse_args() os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(args.gpu) print(\"[info]: use gpu: {}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"]))",
"str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower()",
"to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model,",
"action='store', type=int, default=32) parser.add_argument('--T', action='store', type=float, default=10) parser.add_argument('--alpha', action='store', type=float, default=0.1) args =",
"# T=args.T, # alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet",
"train import test from get_data import import_data from model_zoo import googLeNet, resnet, load_model",
"= utils.ResNetUtils() # my_util = utils.DistillModelUtils( # cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha #",
"# ) # new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new = load_model.load_model(",
"parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir",
"{}\".format(args.load_v)) print(\"[info]: retrain: {}\".format(args.retrain)) print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T))",
"= argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str, default=\"0\") parser.add_argument('--lr', action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int,",
"train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set,",
"get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test(",
"import os import draw_his import train import test from get_data import import_data from",
"train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v,",
"def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif",
"default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\")",
"learning rate: {}\".format(args.lr)) print(\"[info]: epochs: {}\".format(args.epochs)) print(\"[info]: train_version: {}\".format(args.train_v)) print(\"[info]: load_version: {}\".format(args.load_v)) print(\"[info]:",
"version=args.load_v, new_model=new_model, just_weights=False, retrain=args.retrain, to_cuda=True ) train_set, valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False,",
"{}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util =",
"import ensembel_model def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return",
"alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils() # my_util = utils.DistillModelUtils(",
"in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false',",
"('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser",
"cumbersome_model=ensembel_model.my_ensembel_model(), # T=args.T, # alpha=args.alpha # ) # new_model = googLeNet.my_googLeNet new_model =",
"print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) # my_util = utils.GoogLeNetUtils() my_util = utils.ResNetUtils()",
"import test from get_data import import_data from model_zoo import googLeNet, resnet, load_model import",
"True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise",
"train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr, epoch=args.epochs, batch_size=args.batch_size, regularize=args.regularize, train_version=args.train_v, train_loss_function=my_util.loss_for_train, get_true_pred=my_util.get_true_pred, eval_loss_function=my_util.loss_for_eval, detach_pred=my_util.detach_pred,",
"valid_set, test_set = import_data.import_dataset( load_dir=args.load_data_dir, train_to_cuda=False, test_to_cuda=True ) train.train( model=model, train_set=train_set, valid_set=valid_set, lr=args.lr,",
"detach_pred=my_util.detach_pred, learn_rate_schedule=my_util.learn_rate_schedule ) draw_his.draw_his(version=args.train_v, show=False) model = model.cpu() load_model.save_model(args.train_v, model) test.test( test_version=args.train_v, test_set=test_set,",
"action='store', type=float, default=0.001) parser.add_argument('--epochs', action='store', type=int, default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store',",
"default=10) parser.add_argument('--train_v', action='store', type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\")",
"v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no',",
"load_model import utils import ensembel_model def str2bool(v): if v.lower() in ('yes', 'true', 't',",
"import_data from model_zoo import googLeNet, resnet, load_model import utils import ensembel_model def str2bool(v):",
"# new_model = googLeNet.my_googLeNet new_model = resnet.my_resnet model, create_new = load_model.load_model( version=args.load_v, new_model=new_model,",
"'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser()",
"return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--gpu', action='store', type=str,",
"print(\"[info]: regularize: {}\".format(args.regularize)) print(\"[info]: batch_size: {}\".format(args.batch_size)) print(\"[info]: T: {}\".format(args.T)) print(\"[info]: alpha: {}\".format(args.alpha)) #",
"default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir) parser.add_argument('--retrain',",
"import train import test from get_data import import_data from model_zoo import googLeNet, resnet,",
"default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir = \"/media/Data/datasets/cifar/cifar-10-python/data\" parser.add_argument('--load_data_dir', action='store', type=str, default=default_load_data_dir)",
"type=str, default=\"1.0\") parser.add_argument('--load_v', action='store', type=str, default=\"1.0\") default_load_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"get_data/data\") # default_load_data_dir ="
] |
[
"= 84 height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)",
"traj_rewards = [] traj_gaze = [] traj_frames = [] traj_actions = [] print('traj",
"frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory file of frames and",
"gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: # conv_size = 26 # elif gaze_conv_layer",
"range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices =",
"1 elif env_name == \"qbert\": start = 0 skip = 3 elif env_name",
"actions = StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm = [] # normalize",
"1 and have top part masked for ob in stacked_traj: # print(env_name) #normalizing",
"the gaze frequency counts across four frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs",
"for i in range(len(rewards)): if i >= 3: # Sum over the rewards",
"# need to grayscale and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to",
"x in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x for _,",
"in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices",
"range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa) # skip and",
"normalize_state import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return",
"traj_dirs = [] traj_rewards = [] traj_gaze = [] traj_frames = [] traj_actions",
"# DONE: don't mask here! (masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions))",
"import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs",
"# return obs / 255.0 # def normalize(obs, max_val): # # TODO: discard",
"traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x for _, x in sorted( zip(traj_scores,",
"in range(len(frames)): if i >= 3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :,",
"zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze = [x for _, x",
"print(\"num non duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start = 0 skip",
"max to 80x80 grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return",
"= [] human_gaze = [] # print('len demos: ', len(demos)) for data in",
"= [(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa) # skip and stack reward",
"= cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions = [] for",
"human_rewards = [] human_gaze = [] # print('len demos: ', len(demos)) for data",
"make an observation (84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84, 84, 4)) stacked_actions",
"= obs # Take the action of every 4th frame skipped_actions.append(actions[i]) # warp",
"np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for i in range(num_frames): g = gaze[i]",
"obs / 255.0 # def normalize(obs, max_val): # # TODO: discard frames with",
"try only keeping the full demonstrations that end in terminal traj_indices = []",
"and 1 and top section of screen is masked \"\"\" demos = get_sorted_traj_indices(env_name,",
"i % skip == skip - 2: obs_buffer[0] = g if i %",
"terminal traj_indices = [] traj_scores = [] traj_dirs = [] traj_rewards = []",
"max over every 3rd and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total",
"paper and later work.\"\"\" width = 84 height = 84 frame = cv2.cvtColor(image,",
"obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import copy",
"len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))]",
"and 1 and have top part masked for ob in stacked_traj: # print(env_name)",
"def normalize(obs, max_val): # # TODO: discard frames with no gaze # if(max_val",
"separate img_dir defined for every frame of the trajectory as two different trials",
"elif gaze_conv_layer == 4: # conv_size = 7 # else: # print('Invalid Gaze",
"max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so how do we want to get",
"def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done in the Nature paper and",
"+ rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs),",
"mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with softmax # stacked_obs = normalize(stacked_obs,",
"4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic =",
"performance, we can use the trajectory number to index into the demos so",
"the action of every 4th frame skipped_actions.append(actions[i]) # warp max to 80x80 grayscale",
"= np.zeros((2,)) for i in range(num_frames): r = rewards[i] if i % skip",
"traj_dir = path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions",
"sa = [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for",
"= stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs +",
"% skip == skip - 1: obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew)",
"if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f, a))",
"don't mask here! (masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) #",
"<filename>audio_atari/gaze/human_utils.py import numpy as np import cv2 import csv import os import torch",
"pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so how do",
"num_frames = len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames =",
"for i in range(len(actions))] human_demos.append(sa) # skip and stack reward maxed_reward = MaxSkipReward(rew)",
"2: # conv_size = 11 # elif gaze_conv_layer == 3: # conv_size =",
"- 2: obs_buffer[0] = g if i % skip == skip - 1:",
"= non_duplicates # don't skip any demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir,",
"demos by performance, we can use the trajectory number to index into the",
"norm_map = obs/float(max_val) # else: # norm_map = obs # return norm_map #",
"skipped_actions = [] for i in range(num_frames): # TODO: check that i should",
"[] obs_buffer = np.zeros((2,)) for i in range(num_frames): r = rewards[i] if i",
"g = np.squeeze(g) if i % skip == skip - 2: obs_buffer[0] =",
"TODO: confirm best logic for all games start = 0 skip = 3",
"check that i should max before warping. img_name = frames[i] + \".png\" img_dir",
"best logic for all games start = 0 skip = 3 # num_demos",
"= get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos = [] human_rewards = []",
"return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four frames to make",
"[x for _, x in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions =",
"# def normalize(obs, max_val): # # TODO: discard frames with no gaze #",
"in range(len(gaze_frames)): if i >= 3: # Sum over the gaze frequency counts",
"sorted_traj_indices = [x for _, x in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])]",
"to 80x80 grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames,",
"human score\", min(sorted_traj_scores)) # so how do we want to get demos? how",
"width = 84 height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame,",
"= 12 # demos = non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates # don't",
"= g if i % skip == skip - 1: obs_buffer[1] = g",
"stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing #",
"out a subset of demonstrations based on desired performance # first let's sort",
"# return norm_map # need to grayscale and warp to 84x84 def GrayScaleWarpImage(image):",
"max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map created') exit(1) return max_frames def CollapseGaze(gaze_frames,",
"= data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir,",
"obs_buffer[1] = obs # Take the action of every 4th frame skipped_actions.append(actions[i]) #",
"conv_size = 26 # elif gaze_conv_layer == 2: # conv_size = 11 #",
"no gaze # if(max_val != 0): # norm_map = obs/float(max_val) # else: #",
"3: # Sum over the gaze frequency counts across four frames stacked_obs =",
"over every 3rd and 4th observation\"\"\" num_frames = len(rewards) skip = 4 max_frames",
"pair: pair[0])] if use_gaze: sorted_traj_gaze = [x for _, x in sorted( zip(traj_scores,",
"masked for ob in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking",
"and later work.\"\"\" width = 84 height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)",
"StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps as per Ruohan's algorithm h",
"StackReward(rewards): import copy \"\"\"combine every four frames to make an observation\"\"\" stacked =",
"TODO: this heatmap is not normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze",
"for every frame of the trajectory as two different trials could comprise an",
"# TODO: check that i should max before warping. img_name = frames[i] +",
"# norm_map = obs/float(max_val) # else: # norm_map = obs # return norm_map",
"grayscaled, maxpooled, stacks of 4 with normalized values between 0 and 1 and",
"+ gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] # Normalize the gaze mask max_gaze_freq",
"per Ruohan's algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: # conv_size",
"prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for i",
"range(num_frames): r = rewards[i] if i % skip == skip - 2: obs_buffer[0]",
"conv_size) # TODO: this heatmap is not normalized with softmax maxed_gaze = MaxSkipGaze(g,",
"skip - 1: obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan",
"warp max to 80x80 grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions))",
"gaze map created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every",
"images:', num_frames) skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir,",
"trajectory as two different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in",
"for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for",
"if i % skip == skip - 2: obs_buffer[0] = r if i",
"# sa = [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i])",
"= rewards[i] if i % skip == skip - 2: obs_buffer[0] = r",
"Take the action of every 4th frame skipped_actions.append(actions[i]) # warp max to 80x80",
"1: obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import",
"stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] # Normalize the",
"= 0 skip = 1 else: # TODO: confirm best logic for all",
"key=lambda pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames = [x for _, x",
"I'm also going to try only keeping the full demonstrations that end in",
"image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map created') exit(1) return",
"np.amax(stacked_obs) #TODO: normalize gaze with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs =",
"= cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)",
"len(seen_scores)) if env_name == \"spaceinvaders\": start = 0 skip = 3 elif env_name",
"data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name)",
"and have top part masked for ob in stacked_traj: # print(env_name) #normalizing #",
"i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _,",
"skip = 3 elif env_name == \"mspacman\": start = 0 skip = 1",
"= np.amax(stacked_obs) #TODO: normalize gaze with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs",
"= StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps as per Ruohan's algorithm",
"skip = 1 else: # TODO: confirm best logic for all games start",
"= path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir,",
"frames to make an observation (84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84, 84,",
"over the gaze frequency counts across four frames stacked_obs = gaze_frames[i-3] stacked_obs =",
"gaze_conv_layer == 4: # conv_size = 7 # else: # print('Invalid Gaze conv",
"demonstrations are grayscaled, maxpooled, stacks of 4 with normalized values between 0 and",
"4th frame skipped_actions.append(actions[i]) # warp max to 80x80 grayscale image = obs_buffer.max(axis=0) warped",
"max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack every four",
"sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g,",
"stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame in",
"height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions):",
"confirm best logic for all games start = 0 skip = 3 #",
"frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs +",
"[x for _, x in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze:",
"this heatmap is not normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze =",
"norm_map = obs # return norm_map # need to grayscale and warp to",
"== skip - 2: obs_buffer[0] = r if i % skip == skip",
"here! (masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa =",
"data else: indx, score, img_dir, rew, frame, actions = data human_scores.append(score) # traj_dir",
"can use the trajectory number to index into the demos so just #",
"stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): #",
"[] stacked_obs = np.zeros((1,)) for i in range(len(rewards)): if i >= 3: #",
"Note, I'm also going to try only keeping the full demonstrations that end",
"# num_demos = 12 # demos = non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates",
"in stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze",
"# if(max_val != 0): # norm_map = obs/float(max_val) # else: # norm_map =",
"cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if i % skip == skip -",
"= np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if i >= 3: # Sum",
"h = gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: # conv_size = 26 #",
"range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x in sorted( zip(traj_scores, traj_indices), key=lambda pair:",
"and max over every 3rd and 4th observation\"\"\" num_frames = len(rewards) skip =",
"\"spaceinvaders\": start = 0 skip = 3 elif env_name == \"revenge\": start =",
">= 3: # Sum over the rewards across four frames stacked_obs = rewards[i-3]",
"for i in range(num_frames): r = rewards[i] if i % skip == skip",
"3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :,",
"and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done in",
"os import path, listdir import gaze.gaze_heatmap as gh import time # TODO: add",
"trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i",
"heatmap_size): \"\"\"take a list of gaze coordinates and max over every 3rd and",
"many do we have if we remove duplicates? seen_scores = set() non_duplicates =",
"are grayscaled, maxpooled, stacks of 4 with normalized values between 0 and 1",
"sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s,",
"d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s",
"1: obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze",
"img_dir, img_name)) obs_buffer[1] = obs # Take the action of every 4th frame",
"max_frames = [] obs_buffer = np.zeros((2,)) for i in range(num_frames): r = rewards[i]",
"number to index into the demos so just # need to sort indices",
"img_dir defined for every frame of the trajectory as two different trials could",
"normalized values between 0 and 1 and top section of screen is masked",
"in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a)) print(\"num non duplicate scores\",",
"print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards, human_gaze else: return human_demos, human_scores, human_rewards",
"of 4 with normalized values between 0 and 1 and top section of",
"copy \"\"\"combine every four frames to make an observation (84,84)\"\"\" stacked = []",
"max before warping. img_name = frames[i] + \".png\" img_dir = img_dirs[i] if i",
"sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s,",
"range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))])",
"% skip == skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] =",
"and 4th observation\"\"\" num_frames = len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size),",
"[] traj_gaze = [] traj_frames = [] traj_actions = [] print('traj length: ',",
"as per Ruohan's algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: #",
"in range(len(actions))] human_demos.append(sa) # skip and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward =",
"stacked_actions = [] for i in range(len(frames)): if i >= 3: stacked_obs[:, :,",
"sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze = [x for _,",
"= obs if i % skip == skip - 1: obs = cv2.imread(path.join(trajectory_dir,",
"indices based on 'score' game = env_name # Note, I'm also going to",
"and max over every 3rd and 4th observation\"\"\" num_frames = len(gaze) skip =",
"= 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for i in",
"import cv2 import csv import os import torch from os import path, listdir",
"\"\"\"Warp frames to 84x84 as done in the Nature paper and later work.\"\"\"",
"2: obs_buffer[0] = g if i % skip == skip - 1: obs_buffer[1]",
"path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj,",
"conv_size = 11 # elif gaze_conv_layer == 3: # conv_size = 9 #",
"rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs =",
"# else: # print('Invalid Gaze conv layer. Must be between 1-4.') # exit(1)",
"if i >= 3: # Sum over the rewards across four frames stacked_obs",
"to pick out a subset of demonstrations based on desired performance # first",
"running checkpoints from PPO demonstrations are grayscaled, maxpooled, stacks of 4 with normalized",
"img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions",
"import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs / 255.0 # def",
"= np.zeros((1,)) for i in range(len(rewards)): if i >= 3: # Sum over",
"= [] traj_scores = [] traj_dirs = [] traj_rewards = [] traj_gaze =",
"# Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with softmax",
"[] for i in range(len(frames)): if i >= 3: stacked_obs[:, :, 0] =",
"len(rewards) skip = 4 max_frames = [] obs_buffer = np.zeros((2,)) for i in",
"non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates # don't skip any demos return demos",
"logic for all games start = 0 skip = 3 # num_demos =",
"assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack every four frames",
"\"\"\"combine every four frames to make an observation (84,84)\"\"\" stacked = [] stacked_obs",
"an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if",
"# conv_size = 26 # elif gaze_conv_layer == 2: # conv_size = 11",
"MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask = []",
"skip - 2: obs_buffer[0] = g if i % skip == skip -",
"str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj,",
"min(sorted_traj_scores)) # so how do we want to get demos? how many do",
"seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a)) print(\"num non duplicate scores\", len(seen_scores))",
"traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames = [x for _,",
"start = 0 skip = 1 else: # TODO: confirm best logic for",
"\"\"\"stack every four frames to make an observation (84,84,4)\"\"\" stacked = [] stacked_obs",
"f, a)) print(\"num non duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start =",
"demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask here! (masking effects gaze prediction) print(len(frame),",
"img_dir = img_dirs[i] if i % skip == skip - 2: obs =",
"84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done in the Nature paper",
"gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with softmax # stacked_obs =",
"= [x for _, x in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else:",
"grayscale and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done",
"#action for first frame in stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take",
"max_frames def StackReward(rewards): import copy \"\"\"combine every four frames to make an observation\"\"\"",
"pair: pair[0])] sorted_traj_actions = [x for _, x in sorted( zip(traj_scores, traj_actions), key=lambda",
"actions[i]) for i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i in range(len(actions))]",
"stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :, 3]",
"obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for i in range(num_frames): g",
"every 4th frame skipped_actions.append(actions[i]) # warp max to 80x80 grayscale image = obs_buffer.max(axis=0)",
"sorted_traj_frames = [x for _, x in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])]",
"3rd and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip",
"= stacked_obs + rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked",
"not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a)) print(\"num non duplicate",
"frame skipped_actions.append(actions[i]) # warp max to 80x80 grayscale image = obs_buffer.max(axis=0) warped =",
"let's sort the demos by performance, we can use the trajectory number to",
"for extra games from baselines.common.trex_utils import normalize_state import torch.nn.functional as F import torch",
"np.zeros((2,)) for i in range(num_frames): r = rewards[i] if i % skip ==",
"else: # TODO: confirm best logic for all games start = 0 skip",
"def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array of trajectories corresponding to what",
"\"\"\"take a list of rewards and max over every 3rd and 4th observation\"\"\"",
"image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames,",
"masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask here! (masking effects gaze prediction)",
"for _, x in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x",
"cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs # Take the action of every 4th",
"Sum over the rewards across four frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs",
"sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d,",
"dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked def",
"= [] for i in range(num_frames): g = gaze[i] g = np.squeeze(g) if",
":, 0] = frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :, 2] =",
"for i in range(num_frames): # TODO: check that i should max before warping.",
"frames, actions): \"\"\"take a trajectory file of frames and max over every 3rd",
"frames to 84x84 as done in the Nature paper and later work.\"\"\" width",
"of trajectories corresponding to what you would get running checkpoints from PPO demonstrations",
":, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame in stack",
"= stacked_obs + gaze_frames[i] # Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO:",
"top section of screen is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores",
"i in range(len(frames)): if i >= 3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:,",
"any demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array of",
"[] human_gaze = [] # print('len demos: ', len(demos)) for data in demos:",
"9 # elif gaze_conv_layer == 4: # conv_size = 7 # else: #",
"sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a))",
"#TODO: normalize gaze with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs)",
"based on 'score' game = env_name # Note, I'm also going to try",
"over the rewards across four frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs +",
"= path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames =",
"gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs =",
"0 skip = 3 elif env_name == \"mspacman\": start = 0 skip =",
"# print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing # DONE:",
"so just # need to sort indices based on 'score' game = env_name",
"i in range(len(actions))] human_demos.append(sa) # skip and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward",
"else: indx, score, img_dir, rew, frame, actions = data human_scores.append(score) # traj_dir =",
"1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs # Take the action",
"demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array of trajectories",
"sort indices based on 'score' game = env_name # Note, I'm also going",
"frame, actions = data else: indx, score, img_dir, rew, frame, actions = data",
"env_name == \"mspacman\": start = 0 skip = 1 else: # TODO: confirm",
"would get running checkpoints from PPO demonstrations are grayscaled, maxpooled, stacks of 4",
"[] traj_frames = [] traj_actions = [] print('traj length: ', len(dataset.trajectories[game])) for t",
"need to sort indices based on 'score' game = env_name # Note, I'm",
"= len(rewards) skip = 4 max_frames = [] obs_buffer = np.zeros((2,)) for i",
"np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if i >= 3: # Sum over",
"d, r, f, a)) print(\"num non duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\":",
"if i % skip == skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name))",
"be between 0 and 1 and have top part masked for ob in",
"the demos by performance, we can use the trajectory number to index into",
"a list of gaze coordinates and max over every 3rd and 4th observation\"\"\"",
"set() non_duplicates = [] if use_gaze: for i, s, d, r, g, f,",
"i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i",
"traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions =",
"sorted_traj_rewards = [x for _, x in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])]",
"get running checkpoints from PPO demonstrations are grayscaled, maxpooled, stacks of 4 with",
"# Take the action of every 4th frame skipped_actions.append(actions[i]) # warp max to",
"[] for i in range(num_frames): # TODO: check that i should max before",
"[] traj_scores = [] traj_dirs = [] traj_rewards = [] traj_gaze = []",
"actions[i]) for i in range(len(actions))] human_demos.append(sa) # skip and stack reward maxed_reward =",
"do we have if we remove duplicates? seen_scores = set() non_duplicates = []",
"# normalizing # DONE: don't mask here! (masking effects gaze prediction) print(len(frame), len(actions))",
"actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask",
"= h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is not normalized with softmax maxed_gaze",
"across four frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs =",
"4 max_frames = [] obs_buffer = np.zeros((2,)) for i in range(num_frames): r =",
"zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x for _, x in sorted(",
"skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if i",
"\"\"\"combine every four frames to make an observation\"\"\" stacked = [] stacked_obs =",
"f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not",
"import copy \"\"\"stack every four frames to make an observation (84,84,4)\"\"\" stacked =",
"in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f, a)) else: for i,",
"= [] for i in range(len(frames)): if i >= 3: stacked_obs[:, :, 0]",
"exit(1) conv_size = 84 # original image size g = h.createGazeHeatmap(gaze, conv_size) #",
"i, s, d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions):",
"for first frame in stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a",
"obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions = [] for i in",
"3rd and 4th observation\"\"\" num_frames = len(rewards) skip = 4 max_frames = []",
"elif env_name == \"qbert\": start = 0 skip = 3 elif env_name ==",
"== \"mspacman\": start = 0 skip = 1 else: # TODO: confirm best",
"r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not",
"a)) else: for i, s, d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs,",
"with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked",
"obs # Take the action of every 4th frame skipped_actions.append(actions[i]) # warp max",
"checkpoints from PPO demonstrations are grayscaled, maxpooled, stacks of 4 with normalized values",
"numpy as np import cv2 import csv import os import torch from os",
"indx, score, img_dir, rew, frame, actions = data human_scores.append(score) # traj_dir = path.join(data_dir,",
"skipped_actions.append(actions[i]) # warp max to 80x80 grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image)",
"start = 0 skip = 3 elif env_name == \"revenge\": start = 0",
"traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x for _, x in sorted( zip(traj_scores,",
"stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if i",
"traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for every frame of the trajectory as",
"torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape:",
"layer. Must be between 1-4.') # exit(1) conv_size = 84 # original image",
"TODO: discard frames with no gaze # if(max_val != 0): # norm_map =",
"could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in",
"section of screen is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores =",
"demo_norm = [] # normalize values to be between 0 and 1 and",
"range(len(actions))] human_demos.append(sa) # skip and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward)",
"extra games from baselines.common.trex_utils import normalize_state import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False)",
"i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa) #",
"= 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame,",
"sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r,",
"TODO: add masking part for extra games from baselines.common.trex_utils import normalize_state import torch.nn.functional",
"Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with softmax #",
"obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import copy \"\"\"combine every four frames to",
"\"\"\"take a trajectory file of frames and max over every 3rd and 4th",
"#frame = np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a",
"i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))])",
"img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8)",
"sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f,",
"sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path)",
"max_frames = [] skipped_actions = [] for i in range(num_frames): # TODO: check",
"traj_frames = [] traj_actions = [] print('traj length: ', len(dataset.trajectories[game])) for t in",
"i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i",
"dataset, data_dir, use_gaze=False): \"\"\"returns an array of trajectories corresponding to what you would",
"cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return",
"path, listdir import gaze.gaze_heatmap as gh import time # TODO: add masking part",
"stacked def MaxSkipReward(rewards): \"\"\"take a list of rewards and max over every 3rd",
"# generate gaze heatmaps as per Ruohan's algorithm h = gh.DatasetWithHeatmap() # if",
"sorted_traj_gaze = [x for _, x in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])]",
"stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze coordinates and max over",
"frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame",
"in range(len(rewards)): if i >= 3: # Sum over the rewards across four",
"i % skip == skip - 1: obs_buffer[1] = g image = obs_buffer.max(axis=0)",
"normalize(obs, max_val): # # TODO: discard frames with no gaze # if(max_val !=",
"four frames to make an observation (84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size,",
"list of rewards and max over every 3rd and 4th observation\"\"\" num_frames =",
"stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False):",
"to 84x84 as done in the Nature paper and later work.\"\"\" width =",
"3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame in stack return",
"max_frames = [] for i in range(num_frames): g = gaze[i] g = np.squeeze(g)",
"as done in the Nature paper and later work.\"\"\" width = 84 height",
"stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :, 2]",
"= frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first",
"conv_size = 7 # else: # print('Invalid Gaze conv layer. Must be between",
"= MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape)",
"in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa) # skip",
"F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs / 255.0 #",
"interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take",
"0): # norm_map = obs/float(max_val) # else: # norm_map = obs # return",
"of the trajectory as two different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for",
"# need to pick out a subset of demonstrations based on desired performance",
"a list of rewards and max over every 3rd and 4th observation\"\"\" num_frames",
"gaze heatmaps as per Ruohan's algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer ==",
"range(num_frames): g = gaze[i] g = np.squeeze(g) if i % skip == skip",
"zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores))",
"= 84 # original image size g = h.createGazeHeatmap(gaze, conv_size) # TODO: this",
"4 with normalized values between 0 and 1 and top section of screen",
"in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x for _, x",
"img_dir, rew, gaze, frame, actions = data else: indx, score, img_dir, rew, frame,",
"effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i])",
"= [] # normalize values to be between 0 and 1 and have",
"sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x for _, x in",
"# elif gaze_conv_layer == 2: # conv_size = 11 # elif gaze_conv_layer ==",
"human_gaze = [] # print('len demos: ', len(demos)) for data in demos: if",
"comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))])",
"import torch from os import path, listdir import gaze.gaze_heatmap as gh import time",
"4th observation\"\"\" num_frames = len(rewards) skip = 4 max_frames = [] obs_buffer =",
"f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in",
"# conv_size = 11 # elif gaze_conv_layer == 3: # conv_size = 9",
"performance # first let's sort the demos by performance, we can use the",
"g, f, a)) else: for i, s, d, r, f, a in zip(sorted_traj_indices,",
"that end in terminal traj_indices = [] traj_scores = [] traj_dirs = []",
"np.zeros((84, 84, 4)) stacked_actions = [] for i in range(len(frames)): if i >=",
"mask here! (masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa",
"= 0 skip = 1 elif env_name == \"qbert\": start = 0 skip",
"sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for _, x in sorted( zip(traj_scores, traj_dirs),",
"seen_scores = set() non_duplicates = [] if use_gaze: for i, s, d, r,",
"= [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i",
"exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four frames to",
"pair: pair[0])] sorted_traj_rewards = [x for _, x in sorted( zip(traj_scores, traj_rewards), key=lambda",
"four frames to make an observation\"\"\" stacked = [] stacked_obs = np.zeros((1,)) for",
"= 9 # elif gaze_conv_layer == 4: # conv_size = 7 # else:",
"traj_actions = [] print('traj length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score'])",
"= 0 skip = 3 elif env_name == \"revenge\": start = 0 skip",
"for i in range(num_frames): g = gaze[i] g = np.squeeze(g) if i %",
"to sort indices based on 'score' game = env_name # Note, I'm also",
"# exit(1) conv_size = 84 # original image size g = h.createGazeHeatmap(gaze, conv_size)",
"# if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores,",
"= [] obs_buffer = np.zeros((2,)) for i in range(num_frames): r = rewards[i] if",
"= img_dirs[i] if i % skip == skip - 2: obs = cv2.imread(path.join(trajectory_dir,",
"= [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if i >=",
"StackFrames(frames, actions): import copy \"\"\"stack every four frames to make an observation (84,84,4)\"\"\"",
"img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm",
"across four frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs =",
"in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x for _, x",
"is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos =",
"len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards, human_gaze else: return",
"[] skipped_actions = [] for i in range(num_frames): # TODO: check that i",
"max_frames, skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack every four frames to make",
"and max over every 3rd and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) #",
"= np.zeros((84, 84, 4)) stacked_actions = [] for i in range(len(frames)): if i",
"not normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze)",
"frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :,",
"heatmap_size): import copy \"\"\"combine every four frames to make an observation (84,84)\"\"\" stacked",
"3 elif env_name == \"mspacman\": start = 0 skip = 1 else: #",
"= 0 skip = 3 elif env_name == \"mspacman\": start = 0 skip",
"import csv import os import torch from os import path, listdir import gaze.gaze_heatmap",
"traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze = [x for _, x in",
"don't skip any demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an",
"trajectories corresponding to what you would get running checkpoints from PPO demonstrations are",
"i >= 3: # Sum over the rewards across four frames stacked_obs =",
"only keeping the full demonstrations that end in terminal traj_indices = [] traj_scores",
"stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need",
"= env_name # Note, I'm also going to try only keeping the full",
"we have if we remove duplicates? seen_scores = set() non_duplicates = [] if",
"traj_scores = [] traj_dirs = [] traj_rewards = [] traj_gaze = [] traj_frames",
"cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame",
"going to try only keeping the full demonstrations that end in terminal traj_indices",
"s, d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if",
"+ \".png\" img_dir = img_dirs[i] if i % skip == skip - 2:",
"pair[0])] sorted_traj_rewards = [x for _, x in sorted( zip(traj_scores, traj_rewards), key=lambda pair:",
"path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir,",
"listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape,",
"cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions = [] for i",
"env_name == \"qbert\": start = 0 skip = 3 elif env_name == \"mspacman\":",
"import numpy as np import cv2 import csv import os import torch from",
"over every 3rd and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:',",
"[] human_rewards = [] human_gaze = [] # print('len demos: ', len(demos)) for",
"80x80 grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions",
"with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1),",
"non_duplicates # don't skip any demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False):",
"seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f, a)) else: for i, s, d,",
"four frames to make an observation (84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84,",
"image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames",
"= [] stacked_obs = np.zeros((84, 84, 4)) stacked_actions = [] for i in",
"rew, gaze, frame, actions = data else: indx, score, img_dir, rew, frame, actions",
"observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip = 4 sample_pic",
"how do we want to get demos? how many do we have if",
"= len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip = 4 sample_pic = np.random.choice(",
"the demos so just # need to sort indices based on 'score' game",
"[] traj_dirs = [] traj_rewards = [] traj_gaze = [] traj_frames = []",
"scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start = 0 skip = 3 elif",
"= [x for _, x in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards",
"i % skip == skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1]",
"demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask here! (masking",
"rewards and max over every 3rd and 4th observation\"\"\" num_frames = len(rewards) skip",
"skip == skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs",
"traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for every frame of the trajectory",
"if i >= 3: # Sum over the gaze frequency counts across four",
"for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for",
"#normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask",
"demos? how many do we have if we remove duplicates? seen_scores = set()",
"obs_buffer[0] = g if i % skip == skip - 1: obs_buffer[1] =",
"heatmaps as per Ruohan's algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer == 1:",
"full demonstrations that end in terminal traj_indices = [] traj_scores = [] traj_dirs",
"if i % skip == skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name))",
"we can use the trajectory number to index into the demos so just",
"skip = 1 elif env_name == \"qbert\": start = 0 skip = 3",
"_, x in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x for",
"if use_gaze: indx, score, img_dir, rew, gaze, frame, actions = data else: indx,",
"gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze))",
"3: # conv_size = 9 # elif gaze_conv_layer == 4: # conv_size =",
"and top section of screen is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze)",
"# TODO: this heatmap is not normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size)",
"def StackReward(rewards): import copy \"\"\"combine every four frames to make an observation\"\"\" stacked",
"num_frames = len(rewards) skip = 4 max_frames = [] obs_buffer = np.zeros((2,)) for",
"between 0 and 1 and have top part masked for ob in stacked_traj:",
"part for extra games from baselines.common.trex_utils import normalize_state import torch.nn.functional as F import",
"also going to try only keeping the full demonstrations that end in terminal",
"observation (84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)):",
"score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so how do we want to",
"return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick out a subset",
"of every 4th frame skipped_actions.append(actions[i]) # warp max to 80x80 grayscale image =",
"start = 0 skip = 3 elif env_name == \"mspacman\": start = 0",
"every four frames to make an observation\"\"\" stacked = [] stacked_obs = np.zeros((1,))",
"= [] traj_rewards = [] traj_gaze = [] traj_frames = [] traj_actions =",
"gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] # Normalize",
"i, s, d, r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze,",
"human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so how do we want",
"= cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1)",
"to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done in the Nature",
"stacked_obs = stacked_obs + gaze_frames[i] # Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs)",
"gaze_conv_layer == 3: # conv_size = 9 # elif gaze_conv_layer == 4: #",
"= [] stacked_obs = np.zeros((1,)) for i in range(len(rewards)): if i >= 3:",
"# shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a list of rewards and",
"x in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze = [x",
"sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f,",
"an array of trajectories corresponding to what you would get running checkpoints from",
"stacked_actions.append(actions[i-3]) #action for first frame in stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size):",
"= [x for _, x in sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions",
"# elif gaze_conv_layer == 3: # conv_size = 9 # elif gaze_conv_layer ==",
"[x for _, x in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human",
"return obs / 255.0 # def normalize(obs, max_val): # # TODO: discard frames",
"_, x in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores))",
"start = 0 skip = 3 # num_demos = 12 # demos =",
"conv_size = 84 # original image size g = h.createGazeHeatmap(gaze, conv_size) # TODO:",
"MaxSkipReward(rewards): \"\"\"take a list of rewards and max over every 3rd and 4th",
"demonstrations that end in terminal traj_indices = [] traj_scores = [] traj_dirs =",
"# else: # norm_map = obs # return norm_map # need to grayscale",
"use_gaze) human_scores = [] human_demos = [] human_rewards = [] human_gaze = []",
"observation\"\"\" num_frames = len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames",
"= [x for _, x in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores",
"conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0]))",
"# warp max to 80x80 grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped)",
"rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import copy \"\"\"combine every four",
"we remove duplicates? seen_scores = set() non_duplicates = [] if use_gaze: for i,",
"frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height),",
"= gaze[i] g = np.squeeze(g) if i % skip == skip - 2:",
"skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for i",
"softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size)",
"0)) # shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a list of rewards",
"skip = 4 max_frames = [] obs_buffer = np.zeros((2,)) for i in range(num_frames):",
"g = gaze[i] g = np.squeeze(g) if i % skip == skip -",
"values to be between 0 and 1 and have top part masked for",
"with no gaze # if(max_val != 0): # norm_map = obs/float(max_val) # else:",
"= np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for i in range(num_frames): g =",
"in the Nature paper and later work.\"\"\" width = 84 height = 84",
"env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions)",
"1] = frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :, 3] = frames[i]",
"3 # num_demos = 12 # demos = non_duplicates[start:num_demos*skip + start:skip] demos =",
"i >= 3: # Sum over the gaze frequency counts across four frames",
"= 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic",
"[(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa) # skip and stack reward maxed_reward",
"r, f, a)) print(\"num non duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start",
"by performance, we can use the trajectory number to index into the demos",
"the trajectory number to index into the demos so just # need to",
"in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in",
"i % skip == skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0]",
"obs # return norm_map # need to grayscale and warp to 84x84 def",
"- 1: obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards):",
"if i % skip == skip - 1: obs_buffer[1] = g image =",
"in demos: if use_gaze: indx, score, img_dir, rew, gaze, frame, actions = data",
"else: sorted_traj_gaze = [] sorted_traj_frames = [x for _, x in sorted( zip(traj_scores,",
"get demos? how many do we have if we remove duplicates? seen_scores =",
"_, x in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x for",
"zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for _,",
"# so how do we want to get demos? how many do we",
"len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir,",
"84, 4)) stacked_actions = [] for i in range(len(frames)): if i >= 3:",
"# norm_map = obs # return norm_map # need to grayscale and warp",
"what you would get running checkpoints from PPO demonstrations are grayscaled, maxpooled, stacks",
"top part masked for ob in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0])",
"frame, actions = data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir",
"skip any demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array",
"\"mspacman\": start = 0 skip = 1 else: # TODO: confirm best logic",
"[] demo_norm = [] # normalize values to be between 0 and 1",
"obs_buffer[0] = obs if i % skip == skip - 1: obs =",
"if i >= 3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :, 1] =",
"time # TODO: add masking part for extra games from baselines.common.trex_utils import normalize_state",
"print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa",
"= 26 # elif gaze_conv_layer == 2: # conv_size = 11 # elif",
"# demos = non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates # don't skip any",
"skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack every four frames to make an",
"= obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions):",
"in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing",
"i in range(num_frames): # TODO: check that i should max before warping. img_name",
"stacked_obs + rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs = stacked_obs + rewards[i]",
"skip == skip - 1: obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image) if",
"skip == skip - 1: obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew) return",
"[] # print('len demos: ', len(demos)) for data in demos: if use_gaze: indx,",
"= data else: indx, score, img_dir, rew, frame, actions = data human_scores.append(score) #",
"stacked_obs + gaze_frames[i] # Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize",
"= np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions = [] for i in range(num_frames):",
"+ gaze_frames[i] # Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze",
"= r if i % skip == skip - 1: obs_buffer[1] = r",
"stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm = [] #",
"# stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map",
"normalize_state(obs): # return obs / 255.0 # def normalize(obs, max_val): # # TODO:",
"non duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start = 0 skip =",
"s, d, r, g, f, a)) else: for i, s, d, r, f,",
"get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array of trajectories corresponding to what you",
"= normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy()",
"observation\"\"\" stacked = [] stacked_obs = np.zeros((1,)) for i in range(len(rewards)): if i",
"= np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory",
"import time # TODO: add masking part for extra games from baselines.common.trex_utils import",
"skip = 3 elif env_name == \"revenge\": start = 0 skip = 1",
"i should max before warping. img_name = frames[i] + \".png\" img_dir = img_dirs[i]",
"= [] human_demos = [] human_rewards = [] human_gaze = [] # print('len",
"be between 1-4.') # exit(1) conv_size = 84 # original image size g",
"demos: ', len(demos)) for data in demos: if use_gaze: indx, score, img_dir, rew,",
"duplicates? seen_scores = set() non_duplicates = [] if use_gaze: for i, s, d,",
"ob in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) #",
"img_name = frames[i] + \".png\" img_dir = img_dirs[i] if i % skip ==",
"= MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps as",
"actions): \"\"\"take a trajectory file of frames and max over every 3rd and",
"d, r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions):",
"- 2: obs_buffer[0] = r if i % skip == skip - 1:",
"sort the demos by performance, we can use the trajectory number to index",
"for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x in sorted( zip(traj_scores,",
"4: # conv_size = 7 # else: # print('Invalid Gaze conv layer. Must",
"obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map",
"heatmap_size)) for i in range(len(gaze_frames)): if i >= 3: # Sum over the",
"# if gaze_conv_layer == 1: # conv_size = 26 # elif gaze_conv_layer ==",
"[x for _, x in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards =",
"# print('Invalid Gaze conv layer. Must be between 1-4.') # exit(1) conv_size =",
"0 skip = 3 # num_demos = 12 # demos = non_duplicates[start:num_demos*skip +",
"keeping the full demonstrations that end in terminal traj_indices = [] traj_scores =",
"that i should max before warping. img_name = frames[i] + \".png\" img_dir =",
"0 and 1 and have top part masked for ob in stacked_traj: #",
"of screen is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = []",
"work.\"\"\" width = 84 height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame =",
"need to grayscale and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84",
"i in range(len(rewards)): if i >= 3: # Sum over the rewards across",
"to be between 0 and 1 and have top part masked for ob",
"over every 3rd and 4th observation\"\"\" num_frames = len(gaze) skip = 4 obs_buffer",
"for i in range(len(gaze_frames)): if i >= 3: # Sum over the gaze",
"norm_map # need to grayscale and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames",
"gaze frequency counts across four frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs +",
"assert(len(frames)==len(actions)) # print('total images:', num_frames) skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0])))",
"= [x for _, x in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max",
"pair[0])] sorted_traj_actions = [x for _, x in sorted( zip(traj_scores, traj_actions), key=lambda pair:",
"to what you would get running checkpoints from PPO demonstrations are grayscaled, maxpooled,",
"return max_frames def StackReward(rewards): import copy \"\"\"combine every four frames to make an",
"demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos = [] human_rewards =",
"to index into the demos so just # need to sort indices based",
"if i % skip == skip - 1: obs_buffer[1] = r rew =",
"stacked = [] stacked_obs = np.zeros((84, 84, 4)) stacked_actions = [] for i",
"traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x in sorted(",
"gaze coordinates and max over every 3rd and 4th observation\"\"\" num_frames = len(gaze)",
"of gaze coordinates and max over every 3rd and 4th observation\"\"\" num_frames =",
"discard frames with no gaze # if(max_val != 0): # norm_map = obs/float(max_val)",
"elif gaze_conv_layer == 3: # conv_size = 9 # elif gaze_conv_layer == 4:",
"every four frames to make an observation (84,84)\"\"\" stacked = [] stacked_obs =",
"data in demos: if use_gaze: indx, score, img_dir, rew, gaze, frame, actions =",
"height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame =",
"pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions = []",
"human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) #",
"softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze:",
"4)) stacked_actions = [] for i in range(len(frames)): if i >= 3: stacked_obs[:,",
"for all games start = 0 skip = 3 # num_demos = 12",
"coordinates and max over every 3rd and 4th observation\"\"\" num_frames = len(gaze) skip",
"import normalize_state import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): #",
"# don't skip any demos return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns",
"human_demos.append(sa) # skip and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward)",
"# original image size g = h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is",
"do we want to get demos? how many do we have if we",
"actions) # demo_norm_mask = [] demo_norm = [] # normalize values to be",
"stacked_obs = np.zeros((84, 84, 4)) stacked_actions = [] for i in range(len(frames)): if",
"cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame",
"if use_gaze: # generate gaze heatmaps as per Ruohan's algorithm h = gh.DatasetWithHeatmap()",
"- 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if i %",
"so how do we want to get demos? how many do we have",
"[] print('traj length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a",
"r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import copy \"\"\"combine every",
"key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so",
"for _, x in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x",
"range(len(frames)): if i >= 3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :, 1]",
"from baselines.common.trex_utils import normalize_state import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) # def",
"demos = non_duplicates # don't skip any demos return demos def get_preprocessed_trajectories(env_name, dataset,",
"np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions = [] for i in range(num_frames): #",
"action of every 4th frame skipped_actions.append(actions[i]) # warp max to 80x80 grayscale image",
"for i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa)",
"skip - 1: obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def",
"2] = frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for",
"[] sorted_traj_frames = [x for _, x in sorted( zip(traj_scores, traj_frames), key=lambda pair:",
"a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores:",
"observation\"\"\" num_frames = len(rewards) skip = 4 max_frames = [] obs_buffer = np.zeros((2,))",
"0 skip = 1 else: # TODO: confirm best logic for all games",
"def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four frames to make an observation",
"to get demos? how many do we have if we remove duplicates? seen_scores",
"= [] demo_norm = [] # normalize values to be between 0 and",
"CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]),",
"gaze # if(max_val != 0): # norm_map = obs/float(max_val) # else: # norm_map",
"traj_actions), key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) #",
"= [] traj_frames = [] traj_actions = [] print('traj length: ', len(dataset.trajectories[game])) for",
"= GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack",
"norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7)",
"stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick out",
"img_name)) obs_buffer[0] = obs if i % skip == skip - 1: obs",
"GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack every",
"different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for",
"warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done in the",
"demonstrations based on desired performance # first let's sort the demos by performance,",
"grayscale image = obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def",
"heatmap_size), dtype=np.float32) max_frames = [] for i in range(num_frames): g = gaze[i] g",
"sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = [] skipped_actions =",
"2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if i % skip",
"first let's sort the demos by performance, we can use the trajectory number",
"stacked = [] stacked_obs = np.zeros((1,)) for i in range(len(rewards)): if i >=",
"a separate img_dir defined for every frame of the trajectory as two different",
"all games start = 0 skip = 3 # num_demos = 12 #",
"for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for",
"skip == skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs",
"seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a)) print(\"num non duplicate scores\", len(seen_scores)) if",
"26 # elif gaze_conv_layer == 2: # conv_size = 11 # elif gaze_conv_layer",
"for _, x in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores)",
"# conv_size = 9 # elif gaze_conv_layer == 4: # conv_size = 7",
"trajectory file of frames and max over every 3rd and 4th observation\"\"\" num_frames",
"frames to make an observation\"\"\" stacked = [] stacked_obs = np.zeros((1,)) for i",
"copy \"\"\"combine every four frames to make an observation\"\"\" stacked = [] stacked_obs",
"print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so how do we",
"len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for",
"MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory file of frames and max over",
"'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame,",
"11 # elif gaze_conv_layer == 3: # conv_size = 9 # elif gaze_conv_layer",
"from PPO demonstrations are grayscaled, maxpooled, stacks of 4 with normalized values between",
"actions = data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir =",
"# # TODO: discard frames with no gaze # if(max_val != 0): #",
"as two different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))])",
"dataset, use_gaze) human_scores = [] human_demos = [] human_rewards = [] human_gaze =",
"'score' game = env_name # Note, I'm also going to try only keeping",
"traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions']",
"print('nan max gaze map created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy",
"frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs = stacked_obs +",
"== 1: # conv_size = 26 # elif gaze_conv_layer == 2: # conv_size",
"normalize values to be between 0 and 1 and have top part masked",
"= np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer",
"stacks of 4 with normalized values between 0 and 1 and top section",
"start = 0 skip = 1 elif env_name == \"qbert\": start = 0",
"sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r,",
"in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in",
"in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x in sorted( zip(traj_scores, traj_indices), key=lambda",
"== \"spaceinvaders\": start = 0 skip = 3 elif env_name == \"revenge\": start",
"elif gaze_conv_layer == 2: # conv_size = 11 # elif gaze_conv_layer == 3:",
"0] = frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :, 2] = frames[i-1]",
"rewards across four frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs",
"actions) stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm = []",
"/ 255.0 # def normalize(obs, max_val): # # TODO: discard frames with no",
"add masking part for extra games from baselines.common.trex_utils import normalize_state import torch.nn.functional as",
"[] traj_actions = [] print('traj length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t)",
"= gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: # conv_size = 26 # elif",
"print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for i in",
"num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip = 4 sample_pic =",
"len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for",
"# skip and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if",
"\"revenge\": start = 0 skip = 1 elif env_name == \"qbert\": start =",
">= 3: # Sum over the gaze frequency counts across four frames stacked_obs",
"= 11 # elif gaze_conv_layer == 3: # conv_size = 9 # elif",
"in range(num_frames): # TODO: check that i should max before warping. img_name =",
"== 4: # conv_size = 7 # else: # print('Invalid Gaze conv layer.",
"3 elif env_name == \"revenge\": start = 0 skip = 1 elif env_name",
"\"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos = [] human_rewards",
"demos so just # need to sort indices based on 'score' game =",
"[] stacked_obs = np.zeros((84, 84, 4)) stacked_actions = [] for i in range(len(frames)):",
"[] for i in range(num_frames): g = gaze[i] g = np.squeeze(g) if i",
"two different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward']",
"in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for every frame of",
"print('traj length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate",
"[] # normalize values to be between 0 and 1 and have top",
"game = env_name # Note, I'm also going to try only keeping the",
"return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze coordinates and",
"+ gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] #",
"t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for every frame",
"pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for _, x in sorted( zip(traj_scores,",
"frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm =",
"= cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir,",
"frames and max over every 3rd and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions))",
"StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm = [] # normalize values to",
"np import cv2 import csv import os import torch from os import path,",
"copy \"\"\"stack every four frames to make an observation (84,84,4)\"\"\" stacked = []",
"def MaxSkipReward(rewards): \"\"\"take a list of rewards and max over every 3rd and",
"frame of the trajectory as two different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir']",
"rewards[i] if i % skip == skip - 2: obs_buffer[0] = r if",
"in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores:",
"Ruohan's algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: # conv_size =",
"== \"revenge\": start = 0 skip = 1 elif env_name == \"qbert\": start",
"# print('len demos: ', len(demos)) for data in demos: if use_gaze: indx, score,",
"CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four frames to make an observation (84,84)\"\"\"",
"= stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): #",
"# demo_norm_mask = [] demo_norm = [] # normalize values to be between",
"= frames[i] + \".png\" img_dir = img_dirs[i] if i % skip == skip",
"on desired performance # first let's sort the demos by performance, we can",
"for ob in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob))",
"[] if use_gaze: for i, s, d, r, g, f, a in zip(sorted_traj_indices,",
"for i, s, d, r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards,",
"dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for every frame of the",
"should max before warping. img_name = frames[i] + \".png\" img_dir = img_dirs[i] if",
"stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a list",
"x in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames",
"gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for",
"84 # original image size g = h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap",
"Sum over the gaze frequency counts across four frames stacked_obs = gaze_frames[i-3] stacked_obs",
"[x for _, x in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores =",
"make an observation\"\"\" stacked = [] stacked_obs = np.zeros((1,)) for i in range(len(rewards)):",
"\".png\" img_dir = img_dirs[i] if i % skip == skip - 2: obs",
"every 3rd and 4th observation\"\"\" num_frames = len(rewards) skip = 4 max_frames =",
"if i % skip == skip - 2: obs_buffer[0] = g if i",
"norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a",
"# def normalize_state(obs): # return obs / 255.0 # def normalize(obs, max_val): #",
"np.isnan(max_frames).any(): print('nan max gaze map created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import",
"dataset, use_gaze=False): # need to pick out a subset of demonstrations based on",
"score\", min(sorted_traj_scores)) # so how do we want to get demos? how many",
"obs if i % skip == skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir,",
"for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined for every",
"for _, x in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human score\",",
"stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick out a subset of",
"demos = non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates # don't skip any demos",
"gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] # Normalize the gaze mask max_gaze_freq =",
"num_frames) skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0],",
"gh import time # TODO: add masking part for extra games from baselines.common.trex_utils",
"r = rewards[i] if i % skip == skip - 2: obs_buffer[0] =",
"stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0))",
"- 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs # Take the",
"range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x in",
"MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) #",
"import gaze.gaze_heatmap as gh import time # TODO: add masking part for extra",
"torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs /",
"we want to get demos? how many do we have if we remove",
"skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs # Take",
"cv2 import csv import os import torch from os import path, listdir import",
"shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a list of rewards and max",
"in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze = [x for",
"= [] sorted_traj_frames = [x for _, x in sorted( zip(traj_scores, traj_frames), key=lambda",
"use_gaze: for i, s, d, r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs,",
"env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions)",
"gaze[i] g = np.squeeze(g) if i % skip == skip - 2: obs_buffer[0]",
"use_gaze: indx, score, img_dir, rew, gaze, frame, actions = data else: indx, score,",
"7 # else: # print('Invalid Gaze conv layer. Must be between 1-4.') #",
"= path.join(data_dir, env_name) maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions =",
"img_dir, rew, frame, actions = data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name,",
"human_demos = [] human_rewards = [] human_gaze = [] # print('len demos: ',",
"masking part for extra games from baselines.common.trex_utils import normalize_state import torch.nn.functional as F",
"torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs / 255.0 # def normalize(obs,",
"zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s)",
"corresponding to what you would get running checkpoints from PPO demonstrations are grayscaled,",
"= MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions) # demo_norm_mask =",
"skip - 2: obs_buffer[0] = r if i % skip == skip -",
"', len(demos)) for data in demos: if use_gaze: indx, score, img_dir, rew, gaze,",
"# print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards, human_gaze else: return human_demos, human_scores,",
"(1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a list of rewards and max over",
"3rd and 4th observation\"\"\" num_frames = len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size,",
"assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa = [(demo_norm[i],",
"', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return",
"if np.isnan(max_frames).any(): print('nan max gaze map created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size):",
"in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s)",
"np.zeros((1,)) for i in range(len(rewards)): if i >= 3: # Sum over the",
"s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f, a)) else:",
"i % skip == skip - 1: obs_buffer[1] = r rew = obs_buffer.max(axis=0)",
"rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0))",
"= stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] # Normalize the gaze",
"= obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import copy \"\"\"combine every four frames",
"\"\"\"returns an array of trajectories corresponding to what you would get running checkpoints",
"rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick",
"to grayscale and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as",
":, 2] = frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action",
"subset of demonstrations based on desired performance # first let's sort the demos",
"four frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs = stacked_obs",
"stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs",
"img_dirs[i] if i % skip == skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir,",
"print('Invalid Gaze conv layer. Must be between 1-4.') # exit(1) conv_size = 84",
"# print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards, human_gaze",
"= len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = []",
"conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze):",
"remove duplicates? seen_scores = set() non_duplicates = [] if use_gaze: for i, s,",
"frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame,",
"obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs # Take the action of",
"i % skip == skip - 2: obs_buffer[0] = r if i %",
"x in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs =",
"zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames = [x for",
"len(demos)) for data in demos: if use_gaze: indx, score, img_dir, rew, gaze, frame,",
"for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in",
"= [x for _, x in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if",
"non_duplicates.append((i, s, d, r, f, a)) print(\"num non duplicate scores\", len(seen_scores)) if env_name",
"== skip - 2: obs_buffer[0] = g if i % skip == skip",
"use the trajectory number to index into the demos so just # need",
"TODO: check that i should max before warping. img_name = frames[i] + \".png\"",
"3: # Sum over the rewards across four frames stacked_obs = rewards[i-3] stacked_obs",
"(width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames,",
"1: # conv_size = 26 # elif gaze_conv_layer == 2: # conv_size =",
"frames to make an observation (84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size))",
"obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map created') exit(1) return max_frames def",
"pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames = [x for _, x in sorted(",
"data_dir, use_gaze=False): \"\"\"returns an array of trajectories corresponding to what you would get",
"0 skip = 3 elif env_name == \"revenge\": start = 0 skip =",
"= 1 else: # TODO: confirm best logic for all games start =",
"= 3 elif env_name == \"revenge\": start = 0 skip = 1 elif",
"if env_name == \"spaceinvaders\": start = 0 skip = 3 elif env_name ==",
"listdir import gaze.gaze_heatmap as gh import time # TODO: add masking part for",
"actions): import copy \"\"\"stack every four frames to make an observation (84,84,4)\"\"\" stacked",
"rew, frame, actions = data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name, str(indx))",
"for i in range(len(frames)): if i >= 3: stacked_obs[:, :, 0] = frames[i-3]",
"if use_gaze: for i, s, d, r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores,",
"stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze coordinates and max",
"= sorted(traj_scores) sorted_traj_dirs = [x for _, x in sorted( zip(traj_scores, traj_dirs), key=lambda",
"range(num_frames): # TODO: check that i should max before warping. img_name = frames[i]",
"stacked_obs = rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs = stacked_obs + rewards[i-1]",
"frames[i] + \".png\" img_dir = img_dirs[i] if i % skip == skip -",
"normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) #",
"sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i,",
"values between 0 and 1 and top section of screen is masked \"\"\"",
"zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x for _, x in sorted(",
"= [] # print('len demos: ', len(demos)) for data in demos: if use_gaze:",
"have top part masked for ob in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob,",
"pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames = [x for _, x in",
"non_duplicates.append((i, s, d, r, g, f, a)) else: for i, s, d, r,",
"0 skip = 1 elif env_name == \"qbert\": start = 0 skip =",
"you would get running checkpoints from PPO demonstrations are grayscaled, maxpooled, stacks of",
"# Sum over the gaze frequency counts across four frames stacked_obs = gaze_frames[i-3]",
"first frame in stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list",
"in range(num_frames): g = gaze[i] g = np.squeeze(g) if i % skip ==",
"else: for i, s, d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards,",
"frames with no gaze # if(max_val != 0): # norm_map = obs/float(max_val) #",
"= obs # return norm_map # need to grayscale and warp to 84x84",
"indx, score, img_dir, rew, gaze, frame, actions = data else: indx, score, img_dir,",
"warping. img_name = frames[i] + \".png\" img_dir = img_dirs[i] if i % skip",
"sa = [(demo_norm[i], actions[i]) for i in range(len(actions))] human_demos.append(sa) # skip and stack",
"print('total images:', num_frames) skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path =",
"into the demos so just # need to sort indices based on 'score'",
"else: # print('Invalid Gaze conv layer. Must be between 1-4.') # exit(1) conv_size",
"map created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four",
"stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map =",
"a trajectory file of frames and max over every 3rd and 4th observation\"\"\"",
"= frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame in stack return stacked,",
"gaze_frames[i] # Normalize the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with",
"pair[0])] if use_gaze: sorted_traj_gaze = [x for _, x in sorted( zip(traj_scores, traj_gaze),",
"in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human",
"0)) stacked_actions.append(actions[i-3]) #action for first frame in stack return stacked, stacked_actions def MaxSkipGaze(gaze,",
"end in terminal traj_indices = [] traj_scores = [] traj_dirs = [] traj_rewards",
"2: obs_buffer[0] = r if i % skip == skip - 1: obs_buffer[1]",
"x in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min",
"d, r, g, f, a)) else: for i, s, d, r, f, a",
"of frames and max over every 3rd and 4th observation\"\"\" num_frames = len(frames)",
"x in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])] sorted_traj_rewards = [x for _,",
"env_name == \"revenge\": start = 0 skip = 1 elif env_name == \"qbert\":",
"maxed_traj, actions = MaxSkipAndWarpFrames(traj_dir, img_dir, frame, actions) stacked_traj, actions = StackFrames(maxed_traj, actions) #",
"and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: #",
"4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32) max_frames = [] for i in range(num_frames):",
"\"\"\"take a list of gaze coordinates and max over every 3rd and 4th",
"= obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map created') exit(1) return max_frames",
"return stacked def MaxSkipReward(rewards): \"\"\"take a list of rewards and max over every",
"# TODO: confirm best logic for all games start = 0 skip =",
"return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory file of frames",
"# TODO: discard frames with no gaze # if(max_val != 0): # norm_map",
"in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames =",
"os import torch from os import path, listdir import gaze.gaze_heatmap as gh import",
"= F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return",
"pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for _, x in sorted(",
"r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if",
"for i, s, d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames,",
"between 1-4.') # exit(1) conv_size = 84 # original image size g =",
"range(len(gaze_frames)): if i >= 3: # Sum over the gaze frequency counts across",
"4th observation\"\"\" num_frames = len(gaze) skip = 4 obs_buffer = np.zeros((2,)+(heatmap_size, heatmap_size), dtype=np.float32)",
"= [] traj_gaze = [] traj_frames = [] traj_actions = [] print('traj length:",
"dtype=np.uint8) max_frames = [] skipped_actions = [] for i in range(num_frames): # TODO:",
"start:skip] demos = non_duplicates # don't skip any demos return demos def get_preprocessed_trajectories(env_name,",
"else: # norm_map = obs # return norm_map # need to grayscale and",
"r if i % skip == skip - 1: obs_buffer[1] = r rew",
"if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action']",
"max over every 3rd and 4th observation\"\"\" num_frames = len(gaze) skip = 4",
"an observation (84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in",
"to make an observation\"\"\" stacked = [] stacked_obs = np.zeros((1,)) for i in",
"_, x in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze = []",
"255.0 # def normalize(obs, max_val): # # TODO: discard frames with no gaze",
"traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame']",
"based on desired performance # first let's sort the demos by performance, we",
"np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory file",
"len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards, human_gaze else: return human_demos,",
"stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze coordinates",
"the gaze mask max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with softmax # stacked_obs",
"created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four frames",
"if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards,",
"pick out a subset of demonstrations based on desired performance # first let's",
"index into the demos so just # need to sort indices based on",
"obs_buffer = np.zeros((2,)) for i in range(num_frames): r = rewards[i] if i %",
"maxpooled, stacks of 4 with normalized values between 0 and 1 and top",
"= 7 # else: # print('Invalid Gaze conv layer. Must be between 1-4.')",
"demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array of trajectories corresponding to",
"env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask here! (masking effects",
"== \"qbert\": start = 0 skip = 3 elif env_name == \"mspacman\": start",
"seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f, a)) else: for i, s,",
"zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i,",
"a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in",
"img_dirs, frames, actions): \"\"\"take a trajectory file of frames and max over every",
"skip == skip - 2: obs_buffer[0] = g if i % skip ==",
"want to get demos? how many do we have if we remove duplicates?",
"maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps",
"GrayScaleWarpImage(image): \"\"\"Warp frames to 84x84 as done in the Nature paper and later",
"gaze_conv_layer == 2: # conv_size = 11 # elif gaze_conv_layer == 3: #",
"maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ',",
"score, img_dir, rew, frame, actions = data human_scores.append(score) # traj_dir = path.join(data_dir, 'screens',",
"= set() non_duplicates = [] if use_gaze: for i, s, d, r, g,",
"\"qbert\": start = 0 skip = 3 elif env_name == \"mspacman\": start =",
"demo_norm_mask = [] demo_norm = [] # normalize values to be between 0",
"normalizing # DONE: don't mask here! (masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm),",
"# TODO: add masking part for extra games from baselines.common.trex_utils import normalize_state import",
"1 else: # TODO: confirm best logic for all games start = 0",
"gaze, frame, actions = data else: indx, score, img_dir, rew, frame, actions =",
"= 3 # num_demos = 12 # demos = non_duplicates[start:num_demos*skip + start:skip] demos",
"(84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84, 84, 4)) stacked_actions = [] for",
"12 # demos = non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates # don't skip",
"frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame def",
"= StackFrames(maxed_traj, actions) # demo_norm_mask = [] demo_norm = [] # normalize values",
"PPO demonstrations are grayscaled, maxpooled, stacks of 4 with normalized values between 0",
"stacked_obs = stacked_obs + rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return",
"= stacked_obs + rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs = stacked_obs +",
"= cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs # Take the action of every",
"[(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa = [(demo_norm[i], actions[i]) for i in",
"# print('total images:', num_frames) skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path",
"MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze coordinates and max over every 3rd",
"demos: if use_gaze: indx, score, img_dir, rew, gaze, frame, actions = data else:",
"obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if i % skip ==",
"== 3: # conv_size = 9 # elif gaze_conv_layer == 4: # conv_size",
"% skip == skip - 2: obs_buffer[0] = g if i % skip",
"for _, x in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze",
"cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame =",
"part masked for ob in stacked_traj: # print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) #",
"import copy \"\"\"combine every four frames to make an observation (84,84)\"\"\" stacked =",
"= [] traj_dirs = [] traj_rewards = [] traj_gaze = [] traj_frames =",
"= cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if i % skip == skip",
"= g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map created')",
"img_dir, img_name)) obs_buffer[0] = obs if i % skip == skip - 1:",
"import copy \"\"\"combine every four frames to make an observation\"\"\" stacked = []",
"= obs/float(max_val) # else: # norm_map = obs # return norm_map # need",
"four frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs",
"use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for",
"gaze with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map =",
"obs_buffer[0] = r if i % skip == skip - 1: obs_buffer[1] =",
"= frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs),",
"_, x in sorted( zip(traj_scores, traj_rewards), key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze =",
"0 and 1 and top section of screen is masked \"\"\" demos =",
"1 and top section of screen is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset,",
"frequency counts across four frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2]",
"human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps as per Ruohan's algorithm h =",
"size g = h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is not normalized with",
"h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is not normalized with softmax maxed_gaze =",
"key=lambda pair: pair[0])] sorted_traj_actions = [x for _, x in sorted( zip(traj_scores, traj_actions),",
"for data in demos: if use_gaze: indx, score, img_dir, rew, gaze, frame, actions",
"stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3])",
"for _, x in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze =",
"elif env_name == \"revenge\": start = 0 skip = 1 elif env_name ==",
"stacked_obs = np.zeros((1,)) for i in range(len(rewards)): if i >= 3: # Sum",
"if we remove duplicates? seen_scores = set() non_duplicates = [] if use_gaze: for",
"frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame in stack return stacked, stacked_actions",
"if(max_val != 0): # norm_map = obs/float(max_val) # else: # norm_map = obs",
":, 1] = frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :, 3] =",
"max gaze map created') exit(1) return max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine",
"episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i in range(len(dataset.trajectories[game][t]))]) traj_rewards.append([dataset.trajectories[game][t][i]['reward'] for i in range(len(dataset.trajectories[game][t]))]) if use_gaze:",
"range(len(dataset.trajectories[game][t]))]) if use_gaze: traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))])",
"sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze = [] sorted_traj_frames = [x",
"i >= 3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :, 1] = frames[i-2]",
"max over every 3rd and 4th observation\"\"\" num_frames = len(rewards) skip = 4",
"# need to sort indices based on 'score' game = env_name # Note,",
"an observation\"\"\" stacked = [] stacked_obs = np.zeros((1,)) for i in range(len(rewards)): if",
"[] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if i >= 3:",
"between 0 and 1 and top section of screen is masked \"\"\" demos",
"= 3 elif env_name == \"mspacman\": start = 0 skip = 1 else:",
"use_gaze=False): \"\"\"returns an array of trajectories corresponding to what you would get running",
"# conv_size = 7 # else: # print('Invalid Gaze conv layer. Must be",
"desired performance # first let's sort the demos by performance, we can use",
"skip = 4 sample_pic = np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic)",
"print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos, human_scores, human_rewards, human_gaze else:",
"every four frames to make an observation (84,84,4)\"\"\" stacked = [] stacked_obs =",
"np.random.choice( listdir(path.join(trajectory_dir, img_dirs[0]))) image_path = path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer =",
"= np.squeeze(g) if i % skip == skip - 2: obs_buffer[0] = g",
"obs_buffer.max(axis=0) warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions): import",
"i in range(len(gaze_frames)): if i >= 3: # Sum over the gaze frequency",
"obs/float(max_val) # else: # norm_map = obs # return norm_map # need to",
"(masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i],",
"copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take a list of",
"array of trajectories corresponding to what you would get running checkpoints from PPO",
"done in the Nature paper and later work.\"\"\" width = 84 height =",
"normalize gaze with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map",
"max_val): # # TODO: discard frames with no gaze # if(max_val != 0):",
"= [] for i in range(num_frames): # TODO: check that i should max",
"dtype=np.float32) max_frames = [] for i in range(num_frames): g = gaze[i] g =",
"and 4th observation\"\"\" num_frames = len(rewards) skip = 4 max_frames = [] obs_buffer",
"if use_gaze: sorted_traj_gaze = [x for _, x in sorted( zip(traj_scores, traj_gaze), key=lambda",
"stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) stacked_actions.append(actions[i-3]) #action for first frame in stack return stacked, stacked_actions def",
"print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards),",
"every 3rd and 4th observation\"\"\" num_frames = len(gaze) skip = 4 obs_buffer =",
"return norm_map # need to grayscale and warp to 84x84 def GrayScaleWarpImage(image): \"\"\"Warp",
"pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\", min(sorted_traj_scores)) # so how",
"get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick out a subset of demonstrations based",
"algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer == 1: # conv_size = 26",
"- 1: obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max",
"a)) print(\"num non duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start = 0",
"of demonstrations based on desired performance # first let's sort the demos by",
"84 height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame",
"== skip - 1: obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any():",
"elif env_name == \"mspacman\": start = 0 skip = 1 else: # TODO:",
"key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for _, x in",
"traj_gaze.append([dataset.trajectories[game][t][i]['gaze_positions'] for i in range(len(dataset.trajectories[game][t]))]) traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i",
"% skip == skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] =",
"r, g, f, a)) else: for i, s, d, r, f, a in",
"heatmap is not normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze,",
"observation (84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84, 84, 4)) stacked_actions = []",
"print(env_name) #normalizing # demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't",
"= [] skipped_actions = [] for i in range(num_frames): # TODO: check that",
"# print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos),",
"use_gaze: # generate gaze heatmaps as per Ruohan's algorithm h = gh.DatasetWithHeatmap() #",
"in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x",
"sorted(traj_scores) sorted_traj_dirs = [x for _, x in sorted( zip(traj_scores, traj_dirs), key=lambda pair:",
"defined for every frame of the trajectory as two different trials could comprise",
"def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory file of frames and max",
"env_name == \"spaceinvaders\": start = 0 skip = 3 elif env_name == \"revenge\":",
"def StackFrames(frames, actions): import copy \"\"\"stack every four frames to make an observation",
"[x for _, x in sorted( zip(traj_scores, traj_gaze), key=lambda pair: pair[0])] else: sorted_traj_gaze",
"+ rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name,",
"# first let's sort the demos by performance, we can use the trajectory",
"Must be between 1-4.') # exit(1) conv_size = 84 # original image size",
"in range(num_frames): r = rewards[i] if i % skip == skip - 2:",
"the Nature paper and later work.\"\"\" width = 84 height = 84 frame",
"use_gaze: sorted_traj_gaze = [x for _, x in sorted( zip(traj_scores, traj_gaze), key=lambda pair:",
"get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos = [] human_rewards = [] human_gaze",
"print(\"Min human score\", min(sorted_traj_scores)) # so how do we want to get demos?",
"stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i]",
"masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos = []",
"to try only keeping the full demonstrations that end in terminal traj_indices =",
"stacked_obs + gaze_frames[i-1] stacked_obs = stacked_obs + gaze_frames[i] # Normalize the gaze mask",
"not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, g, f, a)) else: for",
"0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick out a",
"# a separate img_dir defined for every frame of the trajectory as two",
"s, d, r, f, a)) print(\"num non duplicate scores\", len(seen_scores)) if env_name ==",
"MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps as per",
">= 3: stacked_obs[:, :, 0] = frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:,",
"to make an observation (84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84, 84, 4))",
"if gaze_conv_layer == 1: # conv_size = 26 # elif gaze_conv_layer == 2:",
"gaze_conv_layer == 1: # conv_size = 26 # elif gaze_conv_layer == 2: #",
"s, d, r, g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames,",
"list of gaze coordinates and max over every 3rd and 4th observation\"\"\" num_frames",
"# elif gaze_conv_layer == 4: # conv_size = 7 # else: # print('Invalid",
"== skip - 1: obs_buffer[1] = r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames",
"num_demos = 12 # demos = non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates #",
"= [] traj_actions = [] print('traj length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]:",
"traj_gaze = [] traj_frames = [] traj_actions = [] print('traj length: ', len(dataset.trajectories[game]))",
"!= 0): # norm_map = obs/float(max_val) # else: # norm_map = obs #",
"return demos def get_preprocessed_trajectories(env_name, dataset, data_dir, use_gaze=False): \"\"\"returns an array of trajectories corresponding",
"as F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs / 255.0",
"= torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) #",
"every 3rd and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames)",
"warped = GrayScaleWarpImage(image) max_frames.append(warped) assert(len(max_frames)==len(skipped_actions)) return max_frames, skipped_actions def StackFrames(frames, actions): import copy",
"len(actions)) assert(len(demo_norm)==len(actions)) # sa = [(demo_norm_mask[i], actions[i]) for i in range(len(demo_norm_mask))] sa =",
"def normalize_state(obs): # return obs / 255.0 # def normalize(obs, max_val): # #",
"games from baselines.common.trex_utils import normalize_state import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) #",
"# masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask here! (masking effects gaze",
"skip = 3 # num_demos = 12 # demos = non_duplicates[start:num_demos*skip + start:skip]",
"stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if i >= 3: #",
"-1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs, frames, actions): \"\"\"take a trajectory file of",
"sorted_traj_gaze = [] sorted_traj_frames = [x for _, x in sorted( zip(traj_scores, traj_frames),",
"np.squeeze(g) if i % skip == skip - 2: obs_buffer[0] = g if",
"# Note, I'm also going to try only keeping the full demonstrations that",
"= norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked def MaxSkipReward(rewards): \"\"\"take",
"and 4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip =",
"return max_frames, skipped_actions def StackFrames(frames, actions): import copy \"\"\"stack every four frames to",
"4th observation\"\"\" num_frames = len(frames) assert(len(frames)==len(actions)) # print('total images:', num_frames) skip = 4",
"normalize(stacked_obs, max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims(",
"rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset,",
"= 4 max_frames = [] obs_buffer = np.zeros((2,)) for i in range(num_frames): r",
"% skip == skip - 1: obs_buffer[1] = g image = obs_buffer.max(axis=0) max_frames.append(image)",
"s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a)) print(\"num non",
"with normalized values between 0 and 1 and top section of screen is",
"cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) #frame = np.expand_dims(frame, -1) return frame def MaxSkipAndWarpFrames(trajectory_dir, img_dirs,",
"non_duplicates = [] if use_gaze: for i, s, d, r, g, f, a",
"DONE: don't mask here! (masking effects gaze prediction) print(len(frame), len(actions)) print(len(demo_norm), len(actions)) assert(len(demo_norm)==len(actions))",
"csv import os import torch from os import path, listdir import gaze.gaze_heatmap as",
"sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d,",
"sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for",
"g image = obs_buffer.max(axis=0) max_frames.append(image) if np.isnan(max_frames).any(): print('nan max gaze map created') exit(1)",
"= 1 elif env_name == \"qbert\": start = 0 skip = 3 elif",
"key=lambda pair: pair[0])] sorted_traj_rewards = [x for _, x in sorted( zip(traj_scores, traj_rewards),",
"human_scores.append(score) # traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj,",
"stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1]",
"Nature paper and later work.\"\"\" width = 84 height = 84 frame =",
"f, a)) else: for i, s, d, r, f, a in zip(sorted_traj_indices, sorted_traj_scores,",
"84x84 as done in the Nature paper and later work.\"\"\" width = 84",
"traj_indices = [] traj_scores = [] traj_dirs = [] traj_rewards = [] traj_gaze",
"== skip - 1: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[1] = obs #",
"of rewards and max over every 3rd and 4th observation\"\"\" num_frames = len(rewards)",
"stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze heatmaps as per Ruohan's",
"range(len(rewards)): if i >= 3: # Sum over the rewards across four frames",
"file of frames and max over every 3rd and 4th observation\"\"\" num_frames =",
"reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate gaze",
"gaze.gaze_heatmap as gh import time # TODO: add masking part for extra games",
"i in range(num_frames): r = rewards[i] if i % skip == skip -",
"if s not in seen_scores: seen_scores.add(s) non_duplicates.append((i, s, d, r, f, a)) print(\"num",
"generate gaze heatmaps as per Ruohan's algorithm h = gh.DatasetWithHeatmap() # if gaze_conv_layer",
"= r rew = obs_buffer.max(axis=0) max_frames.append(rew) return max_frames def StackReward(rewards): import copy \"\"\"combine",
"norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked def MaxSkipReward(rewards):",
"= gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs = stacked_obs + gaze_frames[i-1] stacked_obs",
"stacked_obs + rewards[i-1] stacked_obs = stacked_obs + rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def",
"', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir defined",
"actions = data else: indx, score, img_dir, rew, frame, actions = data human_scores.append(score)",
"# traj_dir = path.join(data_dir, 'screens', env_name, str(indx)) traj_dir = path.join(data_dir, env_name) maxed_traj, actions",
"(84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i in range(len(gaze_frames)): if",
"counts across four frames stacked_obs = gaze_frames[i-3] stacked_obs = stacked_obs + gaze_frames[i-2] stacked_obs",
"original image size g = h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is not",
"= [] human_rewards = [] human_gaze = [] # print('len demos: ', len(demos))",
"== 2: # conv_size = 11 # elif gaze_conv_layer == 3: # conv_size",
"traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x for _, x",
"[] human_demos = [] human_rewards = [] human_gaze = [] # print('len demos:",
"import path, listdir import gaze.gaze_heatmap as gh import time # TODO: add masking",
"duplicate scores\", len(seen_scores)) if env_name == \"spaceinvaders\": start = 0 skip = 3",
"as gh import time # TODO: add masking part for extra games from",
"score, img_dir, rew, gaze, frame, actions = data else: indx, score, img_dir, rew,",
"g if i % skip == skip - 1: obs_buffer[1] = g image",
"g = h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is not normalized with softmax",
"def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to pick out a subset of demonstrations",
"how many do we have if we remove duplicates? seen_scores = set() non_duplicates",
"env_name # Note, I'm also going to try only keeping the full demonstrations",
"image size g = h.createGazeHeatmap(gaze, conv_size) # TODO: this heatmap is not normalized",
"# normalize values to be between 0 and 1 and have top part",
"the trajectory as two different trials could comprise an episode traj_dirs.append([dataset.trajectories[game][t][i]['img_dir'] for i",
"print('len demos: ', len(demos)) for data in demos: if use_gaze: indx, score, img_dir,",
"% skip == skip - 2: obs_buffer[0] = r if i % skip",
"torch from os import path, listdir import gaze.gaze_heatmap as gh import time #",
"84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (width,",
"the full demonstrations that end in terminal traj_indices = [] traj_scores = []",
"F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs), 0)) # shape: (1,7,7) return stacked",
"sorted_traj_dirs = [x for _, x in sorted( zip(traj_scores, traj_dirs), key=lambda pair: pair[0])]",
"every frame of the trajectory as two different trials could comprise an episode",
"to make an observation (84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for",
"just # need to sort indices based on 'score' game = env_name #",
"max_frames.append(rew) return max_frames def StackReward(rewards): import copy \"\"\"combine every four frames to make",
"on 'score' game = env_name # Note, I'm also going to try only",
"skip == skip - 2: obs_buffer[0] = r if i % skip ==",
"trajectory number to index into the demos so just # need to sort",
"frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:, :, 3] = frames[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0))",
"stacked_obs = stacked_obs + rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs = stacked_obs",
"conv_size = 9 # elif gaze_conv_layer == 4: # conv_size = 7 #",
"= CollapseGaze(maxed_gaze, conv_size) human_gaze.append(stacked_gaze) # print('stacked gaze: ', stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]),",
"need to pick out a subset of demonstrations based on desired performance #",
"in terminal traj_indices = [] traj_scores = [] traj_dirs = [] traj_rewards =",
"sorted_traj_actions = [x for _, x in sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])]",
"stack reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze: # generate",
"Gaze conv layer. Must be between 1-4.') # exit(1) conv_size = 84 #",
"img_name)) obs_buffer[1] = obs # Take the action of every 4th frame skipped_actions.append(actions[i])",
"the rewards across four frames stacked_obs = rewards[i-3] stacked_obs = stacked_obs + rewards[i-2]",
"= frames[i-3] stacked_obs[:, :, 1] = frames[i-2] stacked_obs[:, :, 2] = frames[i-1] stacked_obs[:,",
"sorted( zip(traj_scores, traj_frames), key=lambda pair: pair[0])] sorted_traj_actions = [x for _, x in",
"g, f, a in zip(sorted_traj_indices, sorted_traj_scores, sorted_traj_dirs, sorted_traj_rewards, sorted_traj_gaze, sorted_traj_frames, sorted_traj_actions): if s",
"+ rewards[i] stacked.append(np.expand_dims(copy.deepcopy(stacked_obs), 0)) return stacked def get_sorted_traj_indices(env_name, dataset, use_gaze=False): # need to",
"make an observation (84,84)\"\"\" stacked = [] stacked_obs = np.zeros((heatmap_size, heatmap_size)) for i",
"have if we remove duplicates? seen_scores = set() non_duplicates = [] if use_gaze:",
"key=lambda pair: pair[0])] if use_gaze: sorted_traj_gaze = [x for _, x in sorted(",
"games start = 0 skip = 3 # num_demos = 12 # demos",
"1-4.') # exit(1) conv_size = 84 # original image size g = h.createGazeHeatmap(gaze,",
"use_gaze=False): # need to pick out a subset of demonstrations based on desired",
"i in range(num_frames): g = gaze[i] g = np.squeeze(g) if i % skip",
"is not normalized with softmax maxed_gaze = MaxSkipGaze(g, conv_size) stacked_gaze = CollapseGaze(maxed_gaze, conv_size)",
"max_gaze_freq = np.amax(stacked_obs) #TODO: normalize gaze with softmax # stacked_obs = normalize(stacked_obs, max_gaze_freq)",
"max_gaze_freq) stacked_obs = torch.tensor(stacked_obs) norm_map = F.softmax(stacked_obs.view(1,-1), dim=1).view(heatmap_size,heatmap_size) norm_map = norm_map.cpu().detach().numpy() stacked.append(np.expand_dims( copy.deepcopy(stacked_obs),",
"= rewards[i-3] stacked_obs = stacked_obs + rewards[i-2] stacked_obs = stacked_obs + rewards[i-1] stacked_obs",
"= [] if use_gaze: for i, s, d, r, g, f, a in",
"_, x in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs",
"sorted( zip(traj_scores, traj_actions), key=lambda pair: pair[0])] print(\"Max human score\", max(sorted_traj_scores)) print(\"Min human score\",",
"before warping. img_name = frames[i] + \".png\" img_dir = img_dirs[i] if i %",
"frame in stack return stacked, stacked_actions def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of",
"def MaxSkipGaze(gaze, heatmap_size): \"\"\"take a list of gaze coordinates and max over every",
"# Sum over the rewards across four frames stacked_obs = rewards[i-3] stacked_obs =",
"later work.\"\"\" width = 84 height = 84 frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame",
"[] traj_rewards = [] traj_gaze = [] traj_frames = [] traj_actions = []",
"an observation (84,84,4)\"\"\" stacked = [] stacked_obs = np.zeros((84, 84, 4)) stacked_actions =",
"screen is masked \"\"\" demos = get_sorted_traj_indices(env_name, dataset, use_gaze) human_scores = [] human_demos",
"length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) # a separate img_dir",
"in sorted( zip(traj_scores, traj_indices), key=lambda pair: pair[0])] sorted_traj_scores = sorted(traj_scores) sorted_traj_dirs = [x",
"= [] print('traj length: ', len(dataset.trajectories[game])) for t in dataset.trajectories[game]: traj_indices.append(t) traj_scores.append(dataset.trajectories[game][t][-1]['score']) #",
"skip and stack reward maxed_reward = MaxSkipReward(rew) stacked_reward = StackReward(maxed_reward) human_rewards.append(stacked_reward) if use_gaze:",
"conv layer. Must be between 1-4.') # exit(1) conv_size = 84 # original",
"import os import torch from os import path, listdir import gaze.gaze_heatmap as gh",
"path.join(trajectory_dir, img_dirs[0], sample_pic) pic = cv2.imread(image_path) obs_buffer = np.zeros((2,)+pic.shape, dtype=np.uint8) max_frames = []",
"human_scores = [] human_demos = [] human_rewards = [] human_gaze = [] #",
"traj_frames.append([dataset.trajectories[game][t][i]['frame'] for i in range(len(dataset.trajectories[game][t]))]) traj_actions.append([dataset.trajectories[game][t][i]['action'] for i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x",
"# demo_norm_mask.append(preprocess(ob, env_name)[0]) # masking demo_norm.append(normalize_state(ob)) # normalizing # DONE: don't mask here!",
"cv2.ocl.setUseOpenCL(False) # def normalize_state(obs): # return obs / 255.0 # def normalize(obs, max_val):",
"a subset of demonstrations based on desired performance # first let's sort the",
"i in range(len(dataset.trajectories[game][t]))]) sorted_traj_indices = [x for _, x in sorted( zip(traj_scores, traj_indices),",
"max_frames def CollapseGaze(gaze_frames, heatmap_size): import copy \"\"\"combine every four frames to make an",
"== skip - 2: obs = cv2.imread(path.join(trajectory_dir, img_dir, img_name)) obs_buffer[0] = obs if",
"from os import path, listdir import gaze.gaze_heatmap as gh import time # TODO:",
"baselines.common.trex_utils import normalize_state import torch.nn.functional as F import torch cv2.ocl.setUseOpenCL(False) # def normalize_state(obs):",
"as np import cv2 import csv import os import torch from os import",
"= non_duplicates[start:num_demos*skip + start:skip] demos = non_duplicates # don't skip any demos return",
"+ start:skip] demos = non_duplicates # don't skip any demos return demos def",
"stacked_gaze[0].shape) # if(use_gaze): # print(len(human_demos[0]), len(human_rewards[0]), len(human_gaze[0])) # print(len(human_demos), len(human_rewards), len(human_gaze)) return human_demos,",
"= 0 skip = 3 # num_demos = 12 # demos = non_duplicates[start:num_demos*skip"
] |
[
"def flip_bytes(data, offset, count): for i in range(count // 2): start = offset",
"smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2)",
"2) for i in range(0x84, len(data), 4): if data[i : i + 4]",
"'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd',",
"i in range(count // 2): start = offset + i end = offset",
"Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon - Ikuzo! Arashi no",
"'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon - Ikuzo! Arashi no Boukendan",
"'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon",
"data[i : i + 4] == bytearray([0, 0, 1, 0]): flip_bytes(data, i +",
"'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd',",
"+ 2, 2) flip_bytes(data, i + 8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name)",
"offset, count): for i in range(count // 2): start = offset + i",
"2): start = offset + i end = offset + count - i",
"end = offset + count - i - 1 temp = data[start] data[start]",
"flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data,",
"flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for",
"in range(count // 2): start = offset + i end = offset +",
"in range(0x84, len(data), 4): if data[i : i + 4] == bytearray([0, 0,",
"'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd',",
"data[start] data[start] = data[end] data[end] = temp for file_name in file_names: file_path =",
"0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66,",
"'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count): for i in range(count //",
"'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd',",
"'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd',",
"data[start] = data[end] data[end] = temp for file_name in file_names: file_path = os.path.join(base_path,",
"0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50,",
"0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64,",
"4): if data[i : i + 4] == bytearray([0, 0, 1, 0]): flip_bytes(data,",
"i + 8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name) with open(new_file_path, 'wb+') as",
"+ count - i - 1 temp = data[start] data[start] = data[end] data[end]",
"'00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd',",
"i end = offset + count - i - 1 temp = data[start]",
"base_path = os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD',",
"= offset + count - i - 1 temp = data[start] data[start] =",
"WAD', 'Pokemon Fushigi no Dungeon - Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT',",
"Fushigi no Dungeon - Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names",
"Dungeon - Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [",
"flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data,",
"0]): flip_bytes(data, i + 2, 2) flip_bytes(data, i + 8, 4) new_file_path =",
"offset + i end = offset + count - i - 1 temp",
"file_name in file_names: file_path = os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file: data",
"import binascii base_path = os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure",
"'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd',",
"'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd',",
"= 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30,",
"bytearray([0, 0, 1, 0]): flip_bytes(data, i + 2, 2) flip_bytes(data, i + 8,",
"2) flip_bytes(data, i + 8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name) with open(new_file_path,",
"2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for i in range(0x84, len(data), 4):",
"= os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read()) data[3] =",
"2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for i in",
"+ 4] == bytearray([0, 0, 1, 0]): flip_bytes(data, i + 2, 2) flip_bytes(data,",
"bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2)",
"import os import binascii base_path = os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering',",
"[ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd',",
"with open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8,",
"'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon -",
"= [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd',",
"data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data,",
"'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd',",
"<reponame>AnonymousRandomPerson/TranscriptionUtils import os import binascii base_path = os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse",
"'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd',",
"'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count): for i in range(count // 2):",
"open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4)",
"(Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd',",
"if data[i : i + 4] == bytearray([0, 0, 1, 0]): flip_bytes(data, i",
"for i in range(count // 2): start = offset + i end =",
"temp = data[start] data[start] = data[end] data[end] = temp for file_name in file_names:",
"(WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd',",
"data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data,",
"Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd',",
": i + 4] == bytearray([0, 0, 1, 0]): flip_bytes(data, i + 2,",
"flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for i in range(0x84,",
"0x66, 2) for i in range(0x84, len(data), 4): if data[i : i +",
"'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd'",
"'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd',",
"flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data,",
"file_path = os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read()) data[3]",
"0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62,",
"'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd',",
"'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon - Ikuzo! Arashi",
"'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no",
"no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd',",
"'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd',",
"as smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC,",
"os import binascii base_path = os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support',",
"for i in range(0x84, len(data), 4): if data[i : i + 4] ==",
"os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C",
"flip_bytes(data, i + 8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name) with open(new_file_path, 'wb+')",
"+ 8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name) with open(new_file_path, 'wb+') as new_file:",
"'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd',",
"= bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE,",
"data[end] data[end] = temp for file_name in file_names: file_path = os.path.join(base_path, file_name) with",
"0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for i",
"range(count // 2): start = offset + i end = offset + count",
"start = offset + i end = offset + count - i -",
"Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd',",
"'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data,",
"count - i - 1 temp = data[start] data[start] = data[end] data[end] =",
"'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count): for",
"binascii base_path = os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad",
"'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def",
"no Dungeon - Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names =",
"'sys_steal.smd' ] def flip_bytes(data, offset, count): for i in range(count // 2): start",
"Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd',",
"flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for i in range(0x84, len(data), 4): if",
"] def flip_bytes(data, offset, count): for i in range(count // 2): start =",
"flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data,",
"- i - 1 temp = data[start] data[start] = data[end] data[end] = temp",
"'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd',",
"flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data,",
"4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2)",
"'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd',",
"= offset + i end = offset + count - i - 1",
"i - 1 temp = data[start] data[start] = data[end] data[end] = temp for",
"== bytearray([0, 0, 1, 0]): flip_bytes(data, i + 2, 2) flip_bytes(data, i +",
"data[end] = temp for file_name in file_names: file_path = os.path.join(base_path, file_name) with open(file_path,",
"file_name) with open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data,",
"'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd',",
"for file_name in file_names: file_path = os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file:",
"'Pokemon Fushigi no Dungeon - Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content')",
"+ i end = offset + count - i - 1 temp =",
"'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon - Ikuzo! Arashi no Boukendan (Japan)",
"- 1 temp = data[start] data[start] = data[end] data[end] = temp for file_name",
"4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2)",
"= data[end] data[end] = temp for file_name in file_names: file_path = os.path.join(base_path, file_name)",
"'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd',",
"os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi",
"offset + count - i - 1 temp = data[start] data[start] = data[end]",
"2, 2) flip_bytes(data, i + 8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name) with",
"'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd',",
"2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2)",
"flip_bytes(data, i + 2, 2) flip_bytes(data, i + 8, 4) new_file_path = os.path.join(base_path,",
"2) flip_bytes(data, 0x66, 2) for i in range(0x84, len(data), 4): if data[i :",
"i in range(0x84, len(data), 4): if data[i : i + 4] == bytearray([0,",
"in file_names: file_path = os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file: data =",
"1, 0]): flip_bytes(data, i + 2, 2) flip_bytes(data, i + 8, 4) new_file_path",
"// 2): start = offset + i end = offset + count -",
"Squad WAD', 'Pokemon Fushigi no Dungeon - Ikuzo! Arashi no Boukendan (Japan) (WiiWare)',",
"8, 4) new_file_path = os.path.join(base_path, 'Modified', file_name) with open(new_file_path, 'wb+') as new_file: new_file.write(data)",
"0x64, 2) flip_bytes(data, 0x66, 2) for i in range(0x84, len(data), 4): if data[i",
"'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count):",
"'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd',",
"count): for i in range(count // 2): start = offset + i end",
"2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2)",
"'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd',",
"'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count): for i",
"2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4)",
"len(data), 4): if data[i : i + 4] == bytearray([0, 0, 1, 0]):",
"0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C,",
"'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd',",
"range(0x84, len(data), 4): if data[i : i + 4] == bytearray([0, 0, 1,",
"- Ikuzo! Arashi no Boukendan (Japan) (WiiWare)', '00000002_app_OUT', 'content') file_names = [ 'dun_boss.smd',",
"0x30, 2) flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52,",
"'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count): for i in",
"flip_bytes(data, 0x66, 2) for i in range(0x84, len(data), 4): if data[i : i",
"'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd',",
"file_names = [ 'dun_boss.smd', 'dun_bossfloor.smd', 'dun_mount_1.smd', 'dun_mount_2.smd', 'dun_mount.smd', 'endroll.smd', 'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd',",
"'rb') as smd_file: data = bytearray(smd_file.read()) data[3] = 0x6C flip_bytes(data, 0x8, 4) flip_bytes(data,",
"i + 4] == bytearray([0, 0, 1, 0]): flip_bytes(data, i + 2, 2)",
"= data[start] data[start] = data[end] data[end] = temp for file_name in file_names: file_path",
"4] == bytearray([0, 0, 1, 0]): flip_bytes(data, i + 2, 2) flip_bytes(data, i",
"'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ]",
"= temp for file_name in file_names: file_path = os.path.join(base_path, file_name) with open(file_path, 'rb')",
"0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2) flip_bytes(data, 0x46,",
"1 temp = data[start] data[start] = data[end] data[end] = temp for file_name in",
"0x6C flip_bytes(data, 0x8, 4) flip_bytes(data, 0xC, 2) flip_bytes(data, 0xE, 2) flip_bytes(data, 0x30, 2)",
"'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset,",
"file_names: file_path = os.path.join(base_path, file_name) with open(file_path, 'rb') as smd_file: data = bytearray(smd_file.read())",
"flip_bytes(data, 0x46, 2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data,",
"'me_reward.smd', 'me_system.smd', 'me_wave_m.smd', 'me_wave_s.smd', 'me_wind_m.smd', 'me_wind_s.smd', 'no_sound.smd', 'sys_bazar.smd', 'sys_clear.smd', 'sys_map.smd', 'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd',",
"= os.path.join(os.sep, 'Users', 'chenghanngan', 'Documents', 'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon",
"temp for file_name in file_names: file_path = os.path.join(base_path, file_name) with open(file_path, 'rb') as",
"'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd',",
"flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data,",
"'Programs', 'Reverse Engineering', 'Support', 'Adventure Squad WAD', 'Pokemon Fushigi no Dungeon - Ikuzo!",
"0, 1, 0]): flip_bytes(data, i + 2, 2) flip_bytes(data, i + 8, 4)",
"'sys_menu.smd', 'sys_monster.smd', 'sys_shop.smd', 'sys_steal.smd' ] def flip_bytes(data, offset, count): for i in range(count",
"2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2)",
"flip_bytes(data, offset, count): for i in range(count // 2): start = offset +",
"2) flip_bytes(data, 0x4C, 4) flip_bytes(data, 0x50, 2) flip_bytes(data, 0x52, 2) flip_bytes(data, 0x62, 2)",
"i + 2, 2) flip_bytes(data, i + 8, 4) new_file_path = os.path.join(base_path, 'Modified',",
"0x62, 2) flip_bytes(data, 0x64, 2) flip_bytes(data, 0x66, 2) for i in range(0x84, len(data),",
"'ev_1.smd', 'ev_2.smd', 'ev_3.smd', 'ev_4.smd', 'ev_5.smd', 'ev_ed.smd', 'ev_fear.smd', 'ev_op.smd', 'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd',",
"'gameclear.smd', 'gameover.smd', 'me_dunopen.smd', 'me_evolution_e.smd', 'me_evolution.smd', 'me_exclude.smd', 'me_item.smd', 'me_join.smd', 'me_lankup.smd', 'me_lvup.smd', 'me_reward.smd', 'me_system.smd', 'me_wave_m.smd',"
] |
[
": `str` The URL of the file whose permissions are to be changed.",
"Parameters ---------- cmd (`str`): Command to be executed on the device target (`str`):",
"destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy a file to/from NXOS device",
"Retrieve filenames contained in a directory. Do not recurse into subdirectories, only list",
">>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index':",
"filenames contained in a directory. Do not recurse into subdirectories, only list files",
">>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target,",
"used\") def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration",
"mode, timeout_seconds, *args, **kwargs): \"\"\" Change file permissions Parameters ---------- target : `str`",
"implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that",
"module {} \" \"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args,",
"e: raise type(e)('TFTP/FTP server is unreachable') from e # Instanciate a server futlinux",
"... '-rw-' \"\"\" # Extract device from the keyword arguments, if not passed",
"missing, can't proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return",
"be retrieved. timeout_seconds : `int` The number of seconds to wait before aborting",
"file try: futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server created file can't be",
"dir_output : `obj` The OS corresponding `dir` parser object Returns ------- `file_details` :",
"directory_output['permissions'] ... '-rw-' \"\"\" # Extract device from the keyword arguments, if not",
"running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) # copy",
"FileUtils as server # Server FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import",
"`str` The directory whose details are to be retrieved. timeout_seconds : `int` The",
"'69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\" #",
"self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a",
"None Raises ------ Exception When a device object is not present or device",
">>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server,",
"Vrf to be used during copy operation Returns ------- `None` Raises ------ Exception",
"unittest.mock import Mock server = Mock filemode_to_mode = Mock() # Parent inheritance from",
"= FileUtils.from_device(device) # list all files on the device directory 'flash:' >>> directory_output",
"filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils import FileUtils",
"raise type(e)('TFTP/FTP server is unreachable') from e # Instanciate a server futlinux =",
"File path including the protocol, server and file location. timeout_seconds: `str` The number",
"including the protocol, server and file location. timeout_seconds: `str` The number of seconds",
"fu_device = FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300,",
"def stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file details such as",
"except Exception as e: raise type(e)(\"Server created file can't be deleted\") from e",
"libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \" \"does not implement chmod.\".format(self.__module__)) def validateserver(self,",
"checks. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a",
"AttributeError(\"Devisce object is missing, can't proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds,",
"server futlinux = server(testbed=self.testbed) # Check server created file try: futlinux.checkfile(target) except Exception",
"`str` Server address/name Returns ------- `None` Raises ------ Exception When a device object",
"`obj` The OS corresponding `dir` parser object Returns ------- `dict` : Dict of",
"pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: # For apidoc building only from unittest.mock",
"on the running-configuration. Parameters ---------- source: `str` Full path to the copy 'from'",
"file Parameters ---------- source : `str` The URL of the file to be",
"the operation. Returns ------- `None` if operation succeeded. \"\"\" # To be used",
"-------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils instance",
"FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy a",
"date. Raises ------ AttributeError device object not passed in the function call Exception",
"server information given is valid, and if the device can connect to it.",
"timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can be reached and if a temp",
"\"\"\" Copy configuration to/from device Copy configuration on the device or between locations",
"be used during copy operation Returns ------- `None` Raises ------ Exception When a",
"... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract device from the keyword",
"parser object Returns ------- `file_details` : File details including size, permissions, index and",
"file whose details are to be retrieved. timeout_seconds : `int` The number of",
"the device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size']",
"*args, **kwargs): \"\"\" Make sure that the given server information is valid Function",
"file using transfer protocol. Then deletes the file. Parameters ---------- cmd (`str`): Command",
"the protocol, server and file location. timeout_seconds: `str` The number of seconds to",
"... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can be reached and",
"file name. timeout_seconds : `int` Maximum allowed amount of time for the operation.",
"# Instanciate a server futlinux = server(testbed=self.testbed) # Check server created file try:",
"file details such as length and permissions. Parameters ---------- target : `str` The",
"server is unreachable or the protocol used doesn't support remote checks. Examples --------",
"FileUtils # Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device)",
"FileUtils # Instantiate a filetransferutils instance for NXOS device >>> from pyats.utils.fileutils import",
"a filetransferutils instance for NXOS device >>> from pyats.utils.fileutils import FileUtils >>> fu_device",
"timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames",
"the command from the device to server is unreachable or the protocol used",
"level of the given directory. Parameters ---------- target : `str` The directory whose",
"on the device and on the server. Parameters ---------- source: `str` Full path",
"stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \"",
"target : `str` The directory whose details are to be retrieved. timeout_seconds :",
"the new file name. timeout_seconds : `int` Maximum allowed amount of time for",
"used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from device Copy configuration on the",
"# libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \" \"does not implement chmod.\".format(self.__module__)) def",
"top level of the given directory. Parameters ---------- target : `str` The directory",
"device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ...",
"it. It does this by saving `show clock` output to a particular file",
"permissions, index and last modified date. Raises ------ AttributeError device object not passed",
"passed raise an # AttributeError if 'device' not in kwargs: raise AttributeError(\"Devisce object",
"as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \" \"does",
"e # Great success! logger.info(\"Server is ready to be used\") def copyconfiguration(self, source,",
"chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change file permissions Parameters ---------- target",
"Do not recurse into subdirectories, only list files at the top level of",
"used doesn't support remote checks. Examples -------- # FileUtils >>> from pyats.utils.fileutils import",
"= FileUtils.from_device(device) # copy file from server to device running configuration >>> fu_device.copyconfiguration(",
"libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \" \"does not",
"import FileUtils as FileUtilsCommonDeviceBase # Initialize the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase):",
"# Parent inheritance from .. import FileUtils as FileUtilsCommonDeviceBase # Initialize the logger",
"recurse into subdirectories, only list files at the top level of the given",
"the file whose permissions are to be changed. mode : `int` Same format",
"class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy",
"Rename a file Parameters ---------- source : `str` The URL of the file",
"import FileUtils as server # Server FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils",
"of time for the operation. Returns ------- `None` if operation succeeded. \"\"\" #",
"raise type(e)(\"Server created file can't be checked\") from e # Delete server created",
"timeout_seconds, *args, **kwargs): \"\"\" Delete a file Parameters ---------- target : `str` The",
"that verifies if the server information given is valid, and if the device",
"... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args, **kwargs):",
"e: raise type(e)(\"Server created file can't be deleted\") from e # Great success!",
"on the device or between locations supported on the device and on the",
"renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a file Parameters ----------",
"To be used when implemented # import stat as libstat # stat.filemode(output.st_mode) #",
">>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can be",
": `int` Maximum allowed amount of time for the operation. Returns ------- None",
"Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # rename",
"of the file whose permissions are to be changed. mode : `int` Same",
"on the device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>>",
"implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils",
"details including size, permissions, index and last modified date. Raises ------ AttributeError device",
"for NXOS device >>> fu_device = FileUtils.from_device(device) # list the file details on",
"*args, **kwargs): \"\"\" Change file permissions Parameters ---------- target : `str` The URL",
"proceed with\" \" execution\") # Call the parser obj = dir_output(device=device) parsed_output =",
"`str` The URL of the file whose permissions are to be changed. mode",
"a device to any location supported on the device and on the running-configuration.",
"keyword arguments, if not passed raise an # AttributeError if 'device' not in",
"**kwargs): \"\"\" Retrieve filenames contained in a directory. Do not recurse into subdirectories,",
"fu_device = FileUtils.from_device(device) # list the file details on the device 'flash:' directory",
"`int` Same format as `os.chmod`. timeout_seconds : `int` Maximum allowed amount of time",
"server information is valid Function that verifies if the server information given is",
"contained in a directory. Do not recurse into subdirectories, only list files at",
"amount of time for the operation. Returns ------- None Raises ------ Exception When",
"if operation succeeded. \"\"\" # To be used when implemented # import stat",
"file location. timeout_seconds: `str` The number of seconds to wait before aborting the",
"copy operation Returns ------- `None` Raises ------ Exception When a device object is",
"between locations supported on the device and on the server. Parameters ---------- source:",
"renamed. destination : `str` The URL of the new file name. timeout_seconds :",
"= FileUtils.from_device(device) # copy file from device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl',",
"valid Function that verifies if the server information given is valid, and if",
"of seconds to wait before aborting the operation vrf: `str` Vrf to be",
"aborting the operation cmd: `str` Command to be executed on the device used_server:",
"name. timeout_seconds : `int` Maximum allowed amount of time for the operation. Returns",
"instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list all files on",
"**kwargs): \"\"\" Rename a file Parameters ---------- source : `str` The URL of",
"\" execution\") # Call the parser obj = dir_output(device=device) parsed_output = obj.parse() return",
"dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete a",
"e # Instanciate a server futlinux = server(testbed=self.testbed) # Check server created file",
"a file to/from NXOS device Copy any file to/from a device to any",
"source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self,",
"timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a file Parameters ---------- source : `str`",
"size, permissions, index and last modified date. Raises ------ AttributeError device object not",
"copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from device",
"fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd = 'delete",
"cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that the given server information",
"as server # Server FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\",
"delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds,",
"of the new file name. timeout_seconds : `int` Maximum allowed amount of time",
"used when implemented # import stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise",
"server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server",
"from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils import FileUtils as",
"timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file details such as length and permissions.",
"file on device directory 'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300,",
"# Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) #",
"the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd,",
"file to/from a device to any location supported on the device and on",
"apidoc building only from unittest.mock import Mock server = Mock filemode_to_mode = Mock()",
"the device target (`str`): File path including the protocol, server and file location.",
"from .. import FileUtils as FileUtilsCommonDeviceBase # Initialize the logger logger = logging.getLogger(__name__)",
"= obj.parse() return parsed_output def stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve",
"`dir` parser object Returns ------- `dict` : Dict of filename URLs and the",
"timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract",
"to it. It does this by saving `show clock` output to a particular",
"be executed on the device used_server: `str` Server address/name Returns ------- `None` Raises",
"------- `None` if operation succeeded. \"\"\" # To be used when implemented #",
"file from server to device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config',",
"on the device and on the running-configuration. Parameters ---------- source: `str` Full path",
"device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date':",
"of seconds to wait before aborting the operation. dir_output : `obj` The OS",
"raise NotImplementedError(\"The fileutils module {} \" \"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd,",
"from server to device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ...",
"object is missing, can't proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output,",
"number of seconds to wait before aborting the operation. Default is 300 Returns",
"for NXOS device >>> fu_device = FileUtils.from_device(device) # list all files on the",
"timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76',",
"list the file details on the device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl',",
"timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def",
"\"\"\" # To be used when implemented # import stat as libstat #",
"FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try:",
"`str` The number of seconds to wait before aborting the operation vrf: `str`",
"------- None Raises ------ Exception When a device object is not present or",
"allowed amount of time for the operation. Returns ------- None Raises ------ Exception",
"from unittest.mock import Mock server = Mock filemode_to_mode = Mock() # Parent inheritance",
"... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target,",
"new file name. timeout_seconds : `int` Maximum allowed amount of time for the",
"or between locations supported on the device and on the server. Parameters ----------",
"... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def",
"timeout_seconds, *args, **kwargs): \"\"\" Change file permissions Parameters ---------- target : `str` The",
"timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy a file to/from NXOS device Copy",
"implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: # For apidoc",
"Parameters ---------- source: `str` Full path to the copy 'from' location destination: `str`",
"FileUtils.from_device(device) # delete a specific file on device directory 'flash:' >>> directory_output =",
"the device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files']",
"on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\"",
"saving `show clock` output to a particular file using transfer protocol. Then deletes",
"------- `None` Raises ------ Exception When a device object is not present or",
"**kwargs): \"\"\" Copy a file to/from NXOS device Copy any file to/from a",
"device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300',",
"10:25:46 +00:00'} \"\"\" # Extract device from the keyword arguments, if not passed",
"rename the file on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ...",
"during copy operation Returns ------- `None` Raises ------ Exception When a device object",
"building only from unittest.mock import Mock server = Mock filemode_to_mode = Mock() #",
">>> from pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device) # copy file from",
"timeout_seconds='300', device=device) # copy file from server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl',",
"file permissions Parameters ---------- target : `str` The URL of the file whose",
"# Instantiate a filetransferutils instance for NXOS device >>> from pyats.utils.fileutils import FileUtils",
"a file Parameters ---------- source : `str` The URL of the file to",
"whose details are to be retrieved. timeout_seconds : `int` The number of seconds",
"server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file",
"object not passed in the function call Exception Parser encountered an issue Examples",
"import Mock server = Mock filemode_to_mode = Mock() # Parent inheritance from ..",
"modified date. Raises ------ AttributeError device object not passed in the function call",
"parser object Returns ------- `dict` : Dict of filename URLs and the corresponding",
"location. timeout_seconds: `str` The number of seconds to wait before aborting the operation.",
"or the protocol used doesn't support remote checks. Examples -------- # FileUtils >>>",
"remote checks. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate",
"of the file to be renamed. destination : `str` The URL of the",
"= kwargs['device'] else: raise AttributeError(\"Device object is missing, can't proceed with\" \" execution\")",
"the top level of the given directory. Parameters ---------- target : `str` The",
"with\" \" execution\") # Call the parser obj = dir_output(device=device) parsed_output = obj.parse()",
"information is valid Function that verifies if the server information given is valid,",
"as e: raise type(e)(\"Server created file can't be deleted\") from e # Great",
"to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy",
"NXOS device >>> fu_device = FileUtils.from_device(device) # delete a specific file on device",
"Exception as e: raise type(e)('TFTP/FTP server is unreachable') from e # Instanciate a",
"parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained in a directory.",
"device and on the server. Parameters ---------- source: `str` Full path to the",
"class \"\"\" # Logging import logging try: from pyats.utils.fileutils import FileUtils as server",
"type(e)(\"Server created file can't be deleted\") from e # Great success! logger.info(\"Server is",
"from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ...",
"`dict` : Dict of filename URLs and the corresponding info (ex:size) Raises ------",
"fu_device = FileUtils.from_device(device) # delete a specific file on device directory 'flash:' >>>",
": `int` Same format as `os.chmod`. timeout_seconds : `int` Maximum allowed amount of",
"\"\"\" Change file permissions Parameters ---------- target : `str` The URL of the",
"\"\"\" Copy a file to/from NXOS device Copy any file to/from a device",
"# Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying",
"timeout_seconds='300', device=device) # copy running-configuration to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ...",
"# Call the parser obj = dir_output(device=device) parsed_output = obj.parse() return parsed_output def",
"the device or between locations supported on the device and on the server.",
"using transfer protocol. Then deletes the file. Parameters ---------- cmd (`str`): Command to",
"Returns ------- `None` Raises ------ Exception: If the command from the device to",
"copy file from server to device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ...",
"encountered an issue Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils #",
"destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args,",
"# list all files on the device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:',",
"return parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete a file Parameters",
">>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract device from the keyword arguments, if",
"`str` The URL of the file to be renamed. destination : `str` The",
".. import FileUtils as FileUtilsCommonDeviceBase # Initialize the logger logger = logging.getLogger(__name__) class",
"OS corresponding `dir` parser object Returns ------- `file_details` : File details including size,",
"to be used during copy operation Returns ------- `None` Raises ------ Exception When",
"the operation. Returns ------- None Raises ------ Exception When a device object is",
"timeout_seconds: `str` The number of seconds to wait before aborting the operation. Default",
"the file. Parameters ---------- cmd (`str`): Command to be executed on the device",
"from e # Great success! logger.info(\"Server is ready to be used\") def copyconfiguration(self,",
"= FileUtils.from_device(device) # rename the file on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl',",
"on the device used_server: `str` Server address/name Returns ------- `None` Raises ------ Exception",
"to wait before aborting the operation. Returns ------- None Raises ------ Exception When",
"directory 'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" #",
"and if the device can connect to it. It does this by saving",
"details on the device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device)",
"to wait before aborting the operation. Default is 300 Returns ------- `None` Raises",
"reached and if a temp file can ' 'be created') # Send the",
"if the server information given is valid, and if the device can connect",
"configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration",
"connect to it. It does this by saving `show clock` output to a",
"device >>> fu_device = FileUtils.from_device(device) # list all files on the device directory",
"---------- source : `str` The URL of the file to be renamed. destination",
"Then deletes the file. Parameters ---------- cmd (`str`): Command to be executed on",
"fu_device = FileUtils.from_device(device) # copy file from device to server >>> fu_device.copyfile( ...",
"object is missing, can't proceed with\" \" execution\") # Call the parser obj",
"changed. mode : `int` Same format as `os.chmod`. timeout_seconds : `int` Maximum allowed",
"as `os.chmod`. timeout_seconds : `int` Maximum allowed amount of time for the operation.",
"connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can",
"The OS corresponding `dir` parser object Returns ------- `file_details` : File details including",
": `str` The directory whose details are to be retrieved. timeout_seconds : `int`",
"and last modified date. Raises ------ AttributeError device object not passed in the",
"Maximum allowed amount of time for the operation. Returns ------- `None` if operation",
"can ' 'be created') # Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except",
"source, destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy a file to/from NXOS",
"timeout_seconds: `str` The number of seconds to wait before aborting the operation cmd:",
"Make sure that the given server information is valid Function that verifies if",
"copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300', device=device) \"\"\"",
"filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # copy file from",
"Mock() # Parent inheritance from .. import FileUtils as FileUtilsCommonDeviceBase # Initialize the",
"format as `os.chmod`. timeout_seconds : `int` Maximum allowed amount of time for the",
"is valid Function that verifies if the server information given is valid, and",
"file from device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300',",
"file to/from NXOS device Copy any file to/from a device to any location",
"= dir_output(device=device) parsed_output = obj.parse() return parsed_output def stat(self, target, timeout_seconds, dir_output, *args,",
"\" \"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\"",
"device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs):",
"fileutils module {} \" \"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300,",
"filemode_to_mode except ImportError: try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils",
"to server is unreachable or the protocol used doesn't support remote checks. Examples",
"\"\"\" # delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source,",
"destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration to device memory >>> fu_device.copyconfiguration( ...",
"amount of time for the operation. Returns ------- `None` if operation succeeded. \"\"\"",
"= logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args, **kwargs):",
"Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise type(e)('TFTP/FTP",
"logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd, used_server,",
"instance for NXOS device >>> from pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device)",
"target, timeout_seconds, *args, **kwargs): \"\"\" Delete a file Parameters ---------- target : `str`",
"source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file from server to device",
"import stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {}",
"file from server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300',",
"on the server. Parameters ---------- source: `str` Full path to the copy 'from'",
"directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ...",
"object Returns ------- `file_details` : File details including size, permissions, index and last",
"the server. Parameters ---------- source: `str` Full path to the copy 'from' location",
"directory. Do not recurse into subdirectories, only list files at the top level",
"not recurse into subdirectories, only list files at the top level of the",
"given server information is valid Function that verifies if the server information given",
"... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target)",
"# Great success! logger.info(\"Server is ready to be used\") def copyconfiguration(self, source, destination,",
"last modified date. Raises ------ AttributeError device object not passed in the function",
"raise AttributeError(\"Device object is missing, can't proceed with\" \" execution\") # Call the",
"Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if",
"copy running-configuration to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300',",
"of seconds to wait before aborting the operation. Returns ------- None Raises ------",
"`str` The number of seconds to wait before aborting the operation cmd: `str`",
"`str` Full path to the copy 'to' location timeout_seconds: `str` The number of",
">>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration running-configuration",
"arguments, if not passed raise an # AttributeError if 'device' not in kwargs:",
"protocol, server and file location. timeout_seconds: `str` The number of seconds to wait",
"copy file from device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ...",
"= Mock() # Parent inheritance from .. import FileUtils as FileUtilsCommonDeviceBase # Initialize",
"device >>> from pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device) # copy file",
"used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained",
"path including the protocol, server and file location. timeout_seconds: `str` The number of",
"... destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration to device memory >>> fu_device.copyconfiguration(",
"pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device) # copy file from server to",
"device >>> fu_device = FileUtils.from_device(device) # list the file details on the device",
"from device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device)",
"device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs)",
"created file try: futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server created file can't",
"from server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device)",
"timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\"",
"to be changed. mode : `int` Same format as `os.chmod`. timeout_seconds : `int`",
"supported on the device and on the running-configuration. Parameters ---------- source: `str` Full",
"server = Mock filemode_to_mode = Mock() # Parent inheritance from .. import FileUtils",
"server # Server FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode",
"of seconds to wait before aborting the operation cmd: `str` Command to be",
"files on the device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device)",
"Same format as `os.chmod`. timeout_seconds : `int` Maximum allowed amount of time for",
"executed on the device target (`str`): File path including the protocol, server and",
"of filename URLs and the corresponding info (ex:size) Raises ------ AttributeError device object",
"pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils import FileUtils as server",
"fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file from server",
"from the keyword arguments, if not passed raise an # AttributeError if 'device'",
"and permissions. Parameters ---------- target : `str` The URL of the file whose",
"permissions. Parameters ---------- target : `str` The URL of the file whose details",
"operation. Returns ------- None Raises ------ Exception When a device object is not",
"directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self,",
"\"\"\" Make sure that the given server information is valid Function that verifies",
"`None` if operation succeeded. \"\"\" # To be used when implemented # import",
"\"\"\" logger.info('Verifying if server can be reached and if a temp file can",
"# copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300', device=device)",
"raise AttributeError(\"Devisce object is missing, can't proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target,",
"`str` Command to be executed on the device used_server: `str` Server address/name Returns",
"... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file from server to device >>>",
"seconds to wait before aborting the operation cmd: `str` Command to be executed",
"source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a file Parameters ---------- source",
"to wait before aborting the operation vrf: `str` Vrf to be used during",
"a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list all",
"OS corresponding `dir` parser object Returns ------- `dict` : Dict of filename URLs",
"if 'device' not in kwargs: raise AttributeError(\"Devisce object is missing, can't proceed with\"",
"to a particular file using transfer protocol. Then deletes the file. Parameters ----------",
"deleted\") from e # Great success! logger.info(\"Server is ready to be used\") def",
"startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd,",
"only from unittest.mock import Mock server = Mock filemode_to_mode = Mock() # Parent",
"target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained in a directory. Do",
"Parent inheritance from .. import FileUtils as FileUtilsCommonDeviceBase # Initialize the logger logger",
"\"\"\" Retrieve file details such as length and permissions. Parameters ---------- target :",
"device object not passed in the function call Exception Parser encountered an issue",
"------ Exception: If the command from the device to server is unreachable or",
"success! logger.info(\"Server is ready to be used\") def copyconfiguration(self, source, destination, cmd, used_server,",
"`obj` The OS corresponding `dir` parser object Returns ------- `file_details` : File details",
"is 300 Returns ------- `None` Raises ------ Exception: If the command from the",
"a device object is not present or device execution encountered an unexpected behavior.",
"as e: raise type(e)('TFTP/FTP server is unreachable') from e # Instanciate a server",
"can't be deleted\") from e # Great success! logger.info(\"Server is ready to be",
"in kwargs: device = kwargs['device'] else: raise AttributeError(\"Device object is missing, can't proceed",
"{f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename",
"for NXOS device >>> fu_device = FileUtils.from_device(device) # rename the file on the",
"operation. Returns ------- `None` if operation succeeded. \"\"\" # To be used when",
"# Initialize the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination,",
"keyword arguments, if not passed raise an # AttributeError if 'device' in kwargs:",
"of time for the operation. Returns ------- None Raises ------ Exception When a",
"# For apidoc building only from unittest.mock import Mock server = Mock filemode_to_mode",
"device and on the running-configuration. Parameters ---------- source: `str` Full path to the",
"Parameters ---------- target : `str` The URL of the file whose details are",
"dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained in a directory. Do not recurse",
"timeout_seconds: `str` The number of seconds to wait before aborting the operation vrf:",
"number of seconds to wait before aborting the operation vrf: `str` Vrf to",
"20 2018 10:25:46 +00:00'} \"\"\" # Extract device from the keyword arguments, if",
"'device' in kwargs: device = kwargs['device'] else: raise AttributeError(\"Device object is missing, can't",
"# filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: # For apidoc building",
"The number of seconds to wait before aborting the operation. Default is 300",
"------- `dict` : Dict of filename URLs and the corresponding info (ex:size) Raises",
"base class \"\"\" # Logging import logging try: from pyats.utils.fileutils import FileUtils as",
"to the copy 'to' location timeout_seconds: `str` The number of seconds to wait",
"... timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config',",
"logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args,",
"'104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract device from the keyword arguments,",
"Parameters ---------- target : `str` The URL of the file whose permissions are",
"the keyword arguments, if not passed raise an # AttributeError if 'device' not",
"be changed. mode : `int` Same format as `os.chmod`. timeout_seconds : `int` Maximum",
"server and file location. timeout_seconds: `str` The number of seconds to wait before",
"If the command from the device to server is unreachable or the protocol",
"... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can be reached and if a",
">>> from pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils instance for NXOS device",
"from e # Instanciate a server futlinux = server(testbed=self.testbed) # Check server created",
"timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise type(e)('TFTP/FTP server is unreachable') from e",
"import FileUtils # Instanciate a filetransferutils instance for NXOS device >>> fu_device =",
"behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instantiate a",
": `str` The URL of the new file name. timeout_seconds : `int` Maximum",
"parsed_output = obj.parse() return parsed_output def stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\"",
"time for the operation. Returns ------- `None` if operation succeeded. \"\"\" # To",
"# Delete server created file try: futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server",
"... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file from server to",
"\"\"\" # Logging import logging try: from pyats.utils.fileutils import FileUtils as server #",
"core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: # For",
"\\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils import FileUtils as server # Server",
"Copy any file to/from a device to any location supported on the device",
"number of seconds to wait before aborting the operation cmd: `str` Command to",
"`show clock` output to a particular file using transfer protocol. Then deletes the",
"device directory 'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\"",
"if server can be reached and if a temp file can ' 'be",
"fu_device = FileUtils.from_device(device) # copy file from server to device running configuration >>>",
"# stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \" \"does not implement",
"execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target, timeout_seconds,",
"Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # delete",
"type(e)('TFTP/FTP server is unreachable') from e # Instanciate a server futlinux = server(testbed=self.testbed)",
">>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration to",
">>> fu_device = FileUtils.from_device(device) # rename the file on the device 'flash:' directory",
"configuration to/from device Copy configuration on the device or between locations supported on",
"FileUtils >>> fu_device = FileUtils.from_device(device) # copy file from server to device running",
"FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\"",
"logger.info(\"Server is ready to be used\") def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300,",
"the device and on the running-configuration. Parameters ---------- source: `str` Full path to",
"given is valid, and if the device can connect to it. It does",
"'device' not in kwargs: raise AttributeError(\"Devisce object is missing, can't proceed with\" \"",
"can't proceed with\" \" execution\") # Call the parser obj = dir_output(device=device) parsed_output",
"encountered an unexpected behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils",
"operation vrf: `str` Vrf to be used during copy operation Returns ------- `None`",
"specific file on device directory 'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ...",
"retrieved. timeout_seconds : `int` The number of seconds to wait before aborting the",
"# copy file from device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl',",
"is missing, can't proceed with\" \" execution\") # Call the parser obj =",
"device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\"",
"wait before aborting the operation. Returns ------- None Raises ------ Exception When a",
"a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # delete a",
"the device to server is unreachable or the protocol used doesn't support remote",
"copy 'from' location destination: `str` Full path to the copy 'to' location timeout_seconds:",
"any location supported on the device and on the running-configuration. Parameters ---------- source:",
"wait before aborting the operation. dir_output : `obj` The OS corresponding `dir` parser",
"The number of seconds to wait before aborting the operation. Returns ------- None",
"ready to be used\") def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs):",
"instance for NXOS device >>> fu_device = FileUtils.from_device(device) # delete a specific file",
"unexpected behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate",
"NXOS device >>> fu_device = FileUtils.from_device(device) # copy file from device to server",
"permissions Parameters ---------- target : `str` The URL of the file whose permissions",
"**kwargs) except Exception as e: raise type(e)('TFTP/FTP server is unreachable') from e #",
"to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy",
"a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list the",
"to wait before aborting the operation cmd: `str` Command to be executed on",
"the file whose details are to be retrieved. timeout_seconds : `int` The number",
"The URL of the file whose details are to be retrieved. timeout_seconds :",
"obj.parse() return parsed_output def stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file",
"directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract device from the",
">>> fu_device = FileUtils.from_device(device) # delete a specific file on device directory 'flash:'",
"def renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a file Parameters",
"the server information given is valid, and if the device can connect to",
"source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from device Copy",
"the file to be renamed. destination : `str` The URL of the new",
"file on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device)",
"executed on the device used_server: `str` Server address/name Returns ------- `None` Raises ------",
"The number of seconds to wait before aborting the operation vrf: `str` Vrf",
"Command to be executed on the device used_server: `str` Server address/name Returns -------",
"directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699',",
": `int` The number of seconds to wait before aborting the operation. dir_output",
"be used\") def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy",
"to/from device Copy configuration on the device or between locations supported on the",
"wait before aborting the operation vrf: `str` Vrf to be used during copy",
"\"\"\" Retrieve filenames contained in a directory. Do not recurse into subdirectories, only",
"device from the keyword arguments, if not passed raise an # AttributeError if",
"passed raise an # AttributeError if 'device' in kwargs: device = kwargs['device'] else:",
"instance for NXOS device >>> fu_device = FileUtils.from_device(device) # rename the file on",
"'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def",
">>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract device from",
"... timeout_seconds='300', device=device) # copy running-configuration to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config',",
"the given directory. Parameters ---------- target : `str` The directory whose details are",
"is unreachable or the protocol used doesn't support remote checks. Examples -------- #",
"futlinux = server(testbed=self.testbed) # Check server created file try: futlinux.checkfile(target) except Exception as",
"NXOS device >>> fu_device = FileUtils.from_device(device) # rename the file on the device",
"chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that the",
"Great success! logger.info(\"Server is ready to be used\") def copyconfiguration(self, source, destination, cmd,",
"**kwargs) return parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete a file",
"Function that verifies if the server information given is valid, and if the",
"directory whose details are to be retrieved. timeout_seconds : `int` The number of",
"**kwargs): \"\"\" Change file permissions Parameters ---------- target : `str` The URL of",
"device or between locations supported on the device and on the server. Parameters",
"`int` Maximum allowed amount of time for the operation. Returns ------- `None` if",
">>> fu_device = FileUtils.from_device(device) # copy file from device to server >>> fu_device.copyfile(",
"including size, permissions, index and last modified date. Raises ------ AttributeError device object",
"filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # Validate server connectivity",
"Exception Parser encountered an issue Examples -------- # FileUtils >>> from pyats.utils.fileutils import",
">>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file from",
"ImportError: # For apidoc building only from unittest.mock import Mock server = Mock",
"call Exception Parser encountered an issue Examples -------- # FileUtils >>> from pyats.utils.fileutils",
"location timeout_seconds: `str` The number of seconds to wait before aborting the operation",
"Copy configuration on the device or between locations supported on the device and",
"parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target, timeout_seconds, *args,",
"NXOS device Copy any file to/from a device to any location supported on",
"`str` The URL of the file whose details are to be retrieved. timeout_seconds",
"timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change file permissions Parameters",
"server is unreachable') from e # Instanciate a server futlinux = server(testbed=self.testbed) #",
"FileUtils.from_device(device) # copy file from device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ...",
"of seconds to wait before aborting the operation. Default is 300 Returns -------",
"for NXOS device >>> from pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device) #",
"except Exception as e: raise type(e)('TFTP/FTP server is unreachable') from e # Instanciate",
"the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd,",
"if the device can connect to it. It does this by saving `show",
"file can't be checked\") from e # Delete server created file try: futlinux.deletefile(target)",
"Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # copy",
"= fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions':",
"**kwargs): \"\"\" Delete a file Parameters ---------- target : `str` The URL of",
"server. Parameters ---------- source: `str` Full path to the copy 'from' location destination:",
"filetransferutils instance for NXOS device >>> from pyats.utils.fileutils import FileUtils >>> fu_device =",
"dir_output(device=device) parsed_output = obj.parse() return parsed_output def stat(self, target, timeout_seconds, dir_output, *args, **kwargs):",
"\"\"\" Rename a file Parameters ---------- source : `str` The URL of the",
"created file try: futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server created file can't",
"seconds to wait before aborting the operation. Returns ------- None Raises ------ Exception",
"when implemented # import stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The",
"a server futlinux = server(testbed=self.testbed) # Check server created file try: futlinux.checkfile(target) except",
"The URL of the file to be renamed. destination : `str` The URL",
"# Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise",
"copy 'to' location timeout_seconds: `str` The number of seconds to wait before aborting",
"---------- target : `str` The directory whose details are to be retrieved. timeout_seconds",
"URL of the file whose details are to be retrieved. timeout_seconds : `int`",
"File utils common base class \"\"\" # Logging import logging try: from pyats.utils.fileutils",
"Command to be executed on the device target (`str`): File path including the",
"target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change file permissions Parameters ---------- target :",
"filename URLs and the corresponding info (ex:size) Raises ------ AttributeError device object not",
"used during copy operation Returns ------- `None` Raises ------ Exception When a device",
"device Copy configuration on the device or between locations supported on the device",
"operation Returns ------- `None` Raises ------ Exception When a device object is not",
"(ex:size) Raises ------ AttributeError device object not passed in the function call Exception",
"to be retrieved. timeout_seconds : `int` The number of seconds to wait before",
"`str` Full path to the copy 'from' location destination: `str` Full path to",
"destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a file Parameters ---------- source :",
"be reached and if a temp file can ' 'be created') # Send",
"`str` Vrf to be used during copy operation Returns ------- `None` Raises ------",
"Mock server = Mock filemode_to_mode = Mock() # Parent inheritance from .. import",
"def copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy a file",
"'from' location destination: `str` Full path to the copy 'to' location timeout_seconds: `str`",
"all files on the device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300,",
"'Mar 20 2018 10:25:46 +00:00'} \"\"\" # Extract device from the keyword arguments,",
"are to be changed. mode : `int` Same format as `os.chmod`. timeout_seconds :",
"device = kwargs['device'] else: raise AttributeError(\"Device object is missing, can't proceed with\" \"",
"for NXOS device >>> fu_device = FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver(",
"length and permissions. Parameters ---------- target : `str` The URL of the file",
"*args, **kwargs): \"\"\" Copy a file to/from NXOS device Copy any file to/from",
"fu_device = FileUtils.from_device(device) # list all files on the device directory 'flash:' >>>",
"device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy",
"file try: futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server created file can't be",
"# AttributeError if 'device' in kwargs: device = kwargs['device'] else: raise AttributeError(\"Device object",
"'be created') # Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as",
"server to device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300',",
"proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def",
"------ AttributeError device object not passed in the function call Exception Parser encountered",
"be executed on the device target (`str`): File path including the protocol, server",
"created') # Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e:",
"---------- target : `str` The URL of the file whose details are to",
"the operation. dir_output : `obj` The OS corresponding `dir` parser object Returns -------",
">>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions']",
"'to' location timeout_seconds: `str` The number of seconds to wait before aborting the",
"an unexpected behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils #",
"Parameters ---------- source : `str` The URL of the file to be renamed.",
"raise type(e)(\"Server created file can't be deleted\") from e # Great success! logger.info(\"Server",
"+00:00'} \"\"\" # Extract device from the keyword arguments, if not passed raise",
"The number of seconds to wait before aborting the operation cmd: `str` Command",
"or device execution encountered an unexpected behavior. Examples -------- # FileUtils >>> from",
"file Parameters ---------- target : `str` The URL of the file whose details",
"URL of the file whose permissions are to be changed. mode : `int`",
"corresponding `dir` parser object Returns ------- `dict` : Dict of filename URLs and",
"cmd (`str`): Command to be executed on the device target (`str`): File path",
"server can be reached and if a temp file can ' 'be created')",
"import FileUtils >>> fu_device = FileUtils.from_device(device) # copy file from server to device",
"details are to be retrieved. timeout_seconds : `int` The number of seconds to",
"# list the file details on the device 'flash:' directory >>> directory_output =",
"except ImportError: # For apidoc building only from unittest.mock import Mock server =",
"... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file from server to device running",
"timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from device Copy configuration on the device",
"else: raise AttributeError(\"Device object is missing, can't proceed with\" \" execution\") # Call",
"is valid, and if the device can connect to it. It does this",
"type(e)(\"Server created file can't be checked\") from e # Delete server created file",
"FileUtils.from_device(device) # copy file from server to device running configuration >>> fu_device.copyconfiguration( ...",
"number of seconds to wait before aborting the operation. Returns ------- None Raises",
"e: raise type(e)(\"Server created file can't be checked\") from e # Delete server",
"\"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\"",
"= FileUtils.from_device(device) # delete a specific file on device directory 'flash:' >>> directory_output",
"execution\") # Call the parser obj = dir_output(device=device) parsed_output = obj.parse() return parsed_output",
"NXOS device >>> fu_device = FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver( ...",
"'-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\" # Extract device",
"created file can't be deleted\") from e # Great success! logger.info(\"Server is ready",
"\"\"\" File utils common base class \"\"\" # Logging import logging try: from",
"destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file from server to device >>> fu_device.copyfile(",
"# copy file from server to device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py',",
"import \\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils import FileUtils as server #",
"`str` The number of seconds to wait before aborting the operation. Default is",
"given directory. Parameters ---------- target : `str` The directory whose details are to",
"mode : `int` Same format as `os.chmod`. timeout_seconds : `int` Maximum allowed amount",
"self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise type(e)('TFTP/FTP server is unreachable') from",
"def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from",
"timeout_seconds='300', device=device) # copy file from server to device running configuration >>> fu_device.copyfile(",
"that the given server information is valid Function that verifies if the server",
"\"\"\" # Extract device from the keyword arguments, if not passed raise an",
"fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs)",
">>> fu_device = FileUtils.from_device(device) # list all files on the device directory 'flash:'",
"aborting the operation. dir_output : `obj` The OS corresponding `dir` parser object Returns",
"return parsed_output def stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file details",
": `obj` The OS corresponding `dir` parser object Returns ------- `file_details` : File",
"directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'}",
"a directory. Do not recurse into subdirectories, only list files at the top",
"cmd: `str` Command to be executed on the device used_server: `str` Server address/name",
"can be reached and if a temp file can ' 'be created') #",
"from pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device) # copy file from server",
"-------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils instance",
"\"\"\" Delete a file Parameters ---------- target : `str` The URL of the",
"`int` The number of seconds to wait before aborting the operation. Returns -------",
"not in kwargs: raise AttributeError(\"Devisce object is missing, can't proceed with\" \" execution\")",
"= Mock filemode_to_mode = Mock() # Parent inheritance from .. import FileUtils as",
"deletes the file. Parameters ---------- cmd (`str`): Command to be executed on the",
"= 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs):",
"seconds to wait before aborting the operation. Default is 300 Returns ------- `None`",
"... timeout_seconds='300', device=device) # copy file from server to device running configuration >>>",
"Full path to the copy 'to' location timeout_seconds: `str` The number of seconds",
"Change file permissions Parameters ---------- target : `str` The URL of the file",
"passed in the function call Exception Parser encountered an issue Examples -------- #",
"directory. Parameters ---------- target : `str` The directory whose details are to be",
"= server(testbed=self.testbed) # Check server created file try: futlinux.checkfile(target) except Exception as e:",
"# copy file from server to device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl',",
"*args, **kwargs): \"\"\" Retrieve file details such as length and permissions. Parameters ----------",
"filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list all files",
"be renamed. destination : `str` The URL of the new file name. timeout_seconds",
"whose permissions are to be changed. mode : `int` Same format as `os.chmod`.",
"filemode_to_mode = Mock() # Parent inheritance from .. import FileUtils as FileUtilsCommonDeviceBase #",
"file whose permissions are to be changed. mode : `int` Same format as",
"valid, and if the device can connect to it. It does this by",
"server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) #",
"`file_details` : File details including size, permissions, index and last modified date. Raises",
"------- `None` Raises ------ Exception: If the command from the device to server",
"... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config',",
"file from server to device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config',",
"used_server, *args, **kwargs): \"\"\" Copy a file to/from NXOS device Copy any file",
"Exception: If the command from the device to server is unreachable or the",
"execution encountered an unexpected behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import",
"def chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change file permissions Parameters ----------",
"a file Parameters ---------- target : `str` The URL of the file whose",
"unreachable') from e # Instanciate a server futlinux = server(testbed=self.testbed) # Check server",
"on the device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>>",
"\" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target,",
"Parameters ---------- target : `str` The directory whose details are to be retrieved.",
"import logging try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils core",
"is ready to be used\") def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args,",
"FileUtilsCommonDeviceBase # Initialize the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source,",
"'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260'",
"Exception as e: raise type(e)(\"Server created file can't be checked\") from e #",
"The number of seconds to wait before aborting the operation. dir_output : `obj`",
"------- `file_details` : File details including size, permissions, index and last modified date.",
": File details including size, permissions, index and last modified date. Raises ------",
"the corresponding info (ex:size) Raises ------ AttributeError device object not passed in the",
"'76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\" # Extract device from the",
"of the file whose details are to be retrieved. timeout_seconds : `int` The",
"target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd,",
"at the top level of the given directory. Parameters ---------- target : `str`",
"Delete server created file try: futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server created",
"device >>> fu_device = FileUtils.from_device(device) # copy file from device to server >>>",
"Exception as e: raise type(e)(\"Server created file can't be deleted\") from e #",
"Mock filemode_to_mode = Mock() # Parent inheritance from .. import FileUtils as FileUtilsCommonDeviceBase",
"be used when implemented # import stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode)",
"`dir` parser object Returns ------- `file_details` : File details including size, permissions, index",
"logger.info('Verifying if server can be reached and if a temp file can '",
"an # AttributeError if 'device' not in kwargs: raise AttributeError(\"Devisce object is missing,",
"source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration to device memory >>>",
"raise an # AttributeError if 'device' not in kwargs: raise AttributeError(\"Devisce object is",
"\"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make",
"a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # Validate server",
"are to be retrieved. timeout_seconds : `int` The number of seconds to wait",
"an # AttributeError if 'device' in kwargs: device = kwargs['device'] else: raise AttributeError(\"Device",
"function call Exception Parser encountered an issue Examples -------- # FileUtils >>> from",
"configuration on the device or between locations supported on the device and on",
"this by saving `show clock` output to a particular file using transfer protocol.",
"'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\" # Extract device from the keyword",
"e # Delete server created file try: futlinux.deletefile(target) except Exception as e: raise",
"fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\"",
"instance for NXOS device >>> fu_device = FileUtils.from_device(device) # copy file from device",
"URL of the file to be renamed. destination : `str` The URL of",
"issue Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a",
"memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration",
"self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\"",
"FileUtils.from_device(device) # list the file details on the device 'flash:' directory >>> directory_output",
"timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\" Rename a file",
"= fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-'",
"subdirectories, only list files at the top level of the given directory. Parameters",
"The directory whose details are to be retrieved. timeout_seconds : `int` The number",
"Returns ------- `None` if operation succeeded. \"\"\" # To be used when implemented",
"pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils instance for NXOS device >>> from",
"timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete",
"Returns ------- `None` Raises ------ Exception When a device object is not present",
"vrf: `str` Vrf to be used during copy operation Returns ------- `None` Raises",
"**kwargs): \"\"\" Copy configuration to/from device Copy configuration on the device or between",
"FileUtils >>> from pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils instance for NXOS",
"Raises ------ Exception When a device object is not present or device execution",
"device >>> fu_device = FileUtils.from_device(device) # delete a specific file on device directory",
"fu_device = FileUtils.from_device(device) # rename the file on the device 'flash:' directory >>>",
"device >>> fu_device = FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock',",
"futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server created file can't be deleted\") from",
": `int` The number of seconds to wait before aborting the operation. Returns",
"'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\" # Extract",
"device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change",
"{} \" \"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs):",
"import \\ filemode_to_mode except ImportError: # For apidoc building only from unittest.mock import",
"as FileUtilsCommonDeviceBase # Initialize the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self,",
"# copy running-configuration to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ...",
"NXOS device >>> from pyats.utils.fileutils import FileUtils >>> fu_device = FileUtils.from_device(device) # copy",
"running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd,",
"URL of the new file name. timeout_seconds : `int` Maximum allowed amount of",
"the file details on the device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ...",
"file. Parameters ---------- cmd (`str`): Command to be executed on the device target",
"'-rw-' \"\"\" # Extract device from the keyword arguments, if not passed raise",
"Maximum allowed amount of time for the operation. Returns ------- None Raises ------",
"inheritance from .. import FileUtils as FileUtilsCommonDeviceBase # Initialize the logger logger =",
"file details on the device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300,",
"Server FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError:",
"device to server is unreachable or the protocol used doesn't support remote checks.",
"particular file using transfer protocol. Then deletes the file. Parameters ---------- cmd (`str`):",
"device target (`str`): File path including the protocol, server and file location. timeout_seconds:",
"server created file try: futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server created file",
"to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) #",
"fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>>",
"'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log']",
"------ Exception When a device object is not present or device execution encountered",
"the file on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300,",
"and on the server. Parameters ---------- source: `str` Full path to the copy",
"filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # rename the file",
"operation succeeded. \"\"\" # To be used when implemented # import stat as",
"aborting the operation. Returns ------- None Raises ------ Exception When a device object",
"Copy configuration to/from device Copy configuration on the device or between locations supported",
"the device and on the server. Parameters ---------- source: `str` Full path to",
"in a directory. Do not recurse into subdirectories, only list files at the",
"operation cmd: `str` Command to be executed on the device used_server: `str` Server",
"NXOS device >>> fu_device = FileUtils.from_device(device) # list the file details on the",
"address/name Returns ------- `None` Raises ------ Exception When a device object is not",
"if a temp file can ' 'be created') # Send the command try:",
"**kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained in",
"info (ex:size) Raises ------ AttributeError device object not passed in the function call",
"target : `str` The URL of the file whose details are to be",
"try: futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server created file can't be checked\")",
">>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar",
"missing, can't proceed with\" \" execution\") # Call the parser obj = dir_output(device=device)",
"configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,",
">>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file from",
"flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd,",
"is missing, can't proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs)",
"to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ...",
"... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds,",
": `obj` The OS corresponding `dir` parser object Returns ------- `dict` : Dict",
"list all files on the device directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ...",
"fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-',",
"Raises ------ Exception: If the command from the device to server is unreachable",
"output to a particular file using transfer protocol. Then deletes the file. Parameters",
"device=device) # copy running-configuration to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename',",
"logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\"",
"can't proceed with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output",
"logging try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils core implementation",
"kwargs: device = kwargs['device'] else: raise AttributeError(\"Device object is missing, can't proceed with\"",
"cmd, used_server, *args, **kwargs): \"\"\" Copy a file to/from NXOS device Copy any",
"(Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46",
"directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>>",
"ImportError: try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils core implementation",
"Check server created file try: futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server created",
"copyfile(self, source, destination, timeout_seconds, cmd, used_server, *args, **kwargs): \"\"\" Copy a file to/from",
"dir_output, *args, **kwargs): \"\"\" Retrieve file details such as length and permissions. Parameters",
"copy file from server to device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ...",
"except ImportError: try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils core",
"source : `str` The URL of the file to be renamed. destination :",
"unreachable or the protocol used doesn't support remote checks. Examples -------- # FileUtils",
"to the copy 'from' location destination: `str` Full path to the copy 'to'",
"NXOS device >>> fu_device = FileUtils.from_device(device) # list all files on the device",
"does this by saving `show clock` output to a particular file using transfer",
"of the given directory. Parameters ---------- target : `str` The directory whose details",
"When a device object is not present or device execution encountered an unexpected",
"AttributeError if 'device' not in kwargs: raise AttributeError(\"Devisce object is missing, can't proceed",
"kwargs: raise AttributeError(\"Devisce object is missing, can't proceed with\" \" execution\") parsed_output =",
"self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve",
"into subdirectories, only list files at the top level of the given directory.",
"directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd",
"The URL of the new file name. timeout_seconds : `int` Maximum allowed amount",
"protocol. Then deletes the file. Parameters ---------- cmd (`str`): Command to be executed",
"fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can be reached",
"to wait before aborting the operation. dir_output : `obj` The OS corresponding `dir`",
": Dict of filename URLs and the corresponding info (ex:size) Raises ------ AttributeError",
"self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change file permissions",
"Returns ------- None Raises ------ Exception When a device object is not present",
"{'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\"",
"to/from NXOS device Copy any file to/from a device to any location supported",
"clock` output to a particular file using transfer protocol. Then deletes the file.",
"Dict of filename URLs and the corresponding info (ex:size) Raises ------ AttributeError device",
"FileUtils.from_device(device) # list all files on the device directory 'flash:' >>> directory_output =",
"not present or device execution encountered an unexpected behavior. Examples -------- # FileUtils",
"`int` Maximum allowed amount of time for the operation. Returns ------- None Raises",
"# FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils instance for",
"behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a",
"2018 10:25:46 +00:00'} \"\"\" # Extract device from the keyword arguments, if not",
"a particular file using transfer protocol. Then deletes the file. Parameters ---------- cmd",
"def parsed_dir(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained in a",
"Returns ------- `dict` : Dict of filename URLs and the corresponding info (ex:size)",
"temp file can ' 'be created') # Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,",
">>> fu_device = FileUtils.from_device(device) # copy file from server to device running configuration",
": `str` The URL of the file to be renamed. destination : `str`",
"verifies if the server information given is valid, and if the device can",
"before aborting the operation. dir_output : `obj` The OS corresponding `dir` parser object",
"`os.chmod`. timeout_seconds : `int` Maximum allowed amount of time for the operation. Returns",
"created file can't be checked\") from e # Delete server created file try:",
"`str` The URL of the new file name. timeout_seconds : `int` Maximum allowed",
"number of seconds to wait before aborting the operation. dir_output : `obj` The",
"operation. Default is 300 Returns ------- `None` Raises ------ Exception: If the command",
"copy file from server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ...",
"Initialize the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def copyfile(self, source, destination, timeout_seconds,",
"300 Returns ------- `None` Raises ------ Exception: If the command from the device",
">>> from pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils instance for NXOS device",
"The OS corresponding `dir` parser object Returns ------- `dict` : Dict of filename",
"transfer protocol. Then deletes the file. Parameters ---------- cmd (`str`): Command to be",
"the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise type(e)('TFTP/FTP server",
">>> fu_device = FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ...",
"the operation vrf: `str` Vrf to be used during copy operation Returns -------",
"information given is valid, and if the device can connect to it. It",
"*args, **kwargs): \"\"\" Retrieve filenames contained in a directory. Do not recurse into",
"destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from device Copy configuration",
"device can connect to it. It does this by saving `show clock` output",
"from pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils instance for NXOS device >>>",
"Exception When a device object is not present or device execution encountered an",
"command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise type(e)('TFTP/FTP server is",
"---------- source: `str` Full path to the copy 'from' location destination: `str` Full",
"seconds to wait before aborting the operation. dir_output : `obj` The OS corresponding",
"on device directory 'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device)",
"device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) #",
"AttributeError(\"Device object is missing, can't proceed with\" \" execution\") # Call the parser",
"delete a specific file on device directory 'flash:' >>> directory_output = fu_device.deletefile( ...",
"= fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd =",
"as length and permissions. Parameters ---------- target : `str` The URL of the",
"try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception as e: raise type(e)('TFTP/FTP server is unreachable')",
"stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module {} \" \"does not implement chmod.\".format(self.__module__))",
"destination: `str` Full path to the copy 'to' location timeout_seconds: `str` The number",
"FileUtils as FileUtilsCommonDeviceBase # Initialize the logger logger = logging.getLogger(__name__) class FileUtils(FileUtilsCommonDeviceBase): def",
"permissions are to be changed. mode : `int` Same format as `os.chmod`. timeout_seconds",
"from e # Delete server created file try: futlinux.deletefile(target) except Exception as e:",
"for the operation. Returns ------- None Raises ------ Exception When a device object",
"filemode_to_mode except ImportError: # For apidoc building only from unittest.mock import Mock server",
"= FileUtils.from_device(device) # Validate server connectivity >>> fu_device.validateserver( ... target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device)",
"'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete",
"running-configuration. Parameters ---------- source: `str` Full path to the copy 'from' location destination:",
"from pyats.utils.fileutils import FileUtils as server # Server FileUtils core implementation # filemode_to_mode",
"URLs and the corresponding info (ex:size) Raises ------ AttributeError device object not passed",
"Server address/name Returns ------- `None` Raises ------ Exception When a device object is",
"to device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device)",
"server to device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300',",
"if 'device' in kwargs: device = kwargs['device'] else: raise AttributeError(\"Device object is missing,",
"# copy file from server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl',",
"object is not present or device execution encountered an unexpected behavior. Examples --------",
"for the operation. Returns ------- `None` if operation succeeded. \"\"\" # To be",
"NotImplementedError(\"The fileutils module {} \" \"does not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target,",
"as e: raise type(e)(\"Server created file can't be checked\") from e # Delete",
"*args, **kwargs): \"\"\" Copy configuration to/from device Copy configuration on the device or",
"is unreachable') from e # Instanciate a server futlinux = server(testbed=self.testbed) # Check",
"timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that the given server information is valid",
"is not present or device execution encountered an unexpected behavior. Examples -------- #",
"... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output,",
"timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve filenames contained in a directory. Do not",
"core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try: from",
"Extract device from the keyword arguments, if not passed raise an # AttributeError",
"For apidoc building only from unittest.mock import Mock server = Mock filemode_to_mode =",
"'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd, *args, **kwargs): \"\"\"",
"Full path to the copy 'from' location destination: `str` Full path to the",
"with\" \" execution\") parsed_output = self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self,",
"the device used_server: `str` Server address/name Returns ------- `None` Raises ------ Exception When",
"not passed raise an # AttributeError if 'device' in kwargs: device = kwargs['device']",
"server created file try: futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server created file",
"for NXOS device >>> fu_device = FileUtils.from_device(device) # delete a specific file on",
"**kwargs): \"\"\" Retrieve file details such as length and permissions. Parameters ---------- target",
"to be executed on the device target (`str`): File path including the protocol,",
"a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # copy file",
"timeout_seconds : `int` The number of seconds to wait before aborting the operation.",
"Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # Validate",
"except Exception as e: raise type(e)(\"Server created file can't be checked\") from e",
"can't be checked\") from e # Delete server created file try: futlinux.deletefile(target) except",
"fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) # copy file from server",
"\"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode, timeout_seconds, *args, **kwargs): \"\"\" Change file",
"AttributeError device object not passed in the function call Exception Parser encountered an",
"stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file details such as length",
"object Returns ------- `dict` : Dict of filename URLs and the corresponding info",
"index and last modified date. Raises ------ AttributeError device object not passed in",
"= self.parsed_dir(target=target, timeout_seconds=timeout_seconds, dir_output=dir_output, **kwargs) return parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs):",
"to be renamed. destination : `str` The URL of the new file name.",
"device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file",
"wait before aborting the operation. Default is 300 Returns ------- `None` Raises ------",
"parsed_output def stat(self, target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file details such",
">>> fu_device = FileUtils.from_device(device) # list the file details on the device 'flash:'",
"destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds,",
"fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs)",
"implemented # import stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils",
"... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file from server to",
"device=device) # copy file from server to device >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ...",
"parsed_output def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete a file Parameters ----------",
"... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration(",
"the device can connect to it. It does this by saving `show clock`",
"the operation. Default is 300 Returns ------- `None` Raises ------ Exception: If the",
"and the corresponding info (ex:size) Raises ------ AttributeError device object not passed in",
"Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils",
"deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete a file Parameters ---------- target :",
"target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that the given server information is",
"support remote checks. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils #",
"# Logging import logging try: from pyats.utils.fileutils import FileUtils as server # Server",
"Raises ------ AttributeError device object not passed in the function call Exception Parser",
"location supported on the device and on the running-configuration. Parameters ---------- source: `str`",
"target, timeout_seconds, dir_output, *args, **kwargs): \"\"\" Retrieve file details such as length and",
"to device running configuration >>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device)",
"device >>> fu_device = FileUtils.from_device(device) # rename the file on the device 'flash:'",
"the copy 'from' location destination: `str` Full path to the copy 'to' location",
"pyats.utils.fileutils import FileUtils as server # Server FileUtils core implementation # filemode_to_mode from",
"`int` The number of seconds to wait before aborting the operation. dir_output :",
"before aborting the operation. Default is 300 Returns ------- `None` Raises ------ Exception:",
"validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that the given server",
"doesn't support remote checks. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils",
"FileUtils.from_device(device) # rename the file on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ...",
"not passed raise an # AttributeError if 'device' not in kwargs: raise AttributeError(\"Devisce",
"' 'be created') # Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs) except Exception",
"such as length and permissions. Parameters ---------- target : `str` The URL of",
"def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure that the given",
"details such as length and permissions. Parameters ---------- target : `str` The URL",
"Instanciate a server futlinux = server(testbed=self.testbed) # Check server created file try: futlinux.checkfile(target)",
"be checked\") from e # Delete server created file try: futlinux.deletefile(target) except Exception",
"from server to device running configuration >>> fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ...",
"device to server >>> fu_device.copyfile( ... source='flash:/memleak.tcl', ... destination='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... timeout_seconds='300', device=device) #",
"a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # rename the",
"list files at the top level of the given directory. Parameters ---------- target",
"if not passed raise an # AttributeError if 'device' in kwargs: device =",
"to/from a device to any location supported on the device and on the",
"locations supported on the device and on the server. Parameters ---------- source: `str`",
"before aborting the operation. Returns ------- None Raises ------ Exception When a device",
"target : `str` The URL of the file whose permissions are to be",
"device=device) # copy file from server to device running configuration >>> fu_device.copyfile( ...",
"`None` Raises ------ Exception: If the command from the device to server is",
": `str` The URL of the file whose details are to be retrieved.",
"a temp file can ' 'be created') # Send the command try: self.send_cli_to_device(cli=cmd,",
"(`str`): File path including the protocol, server and file location. timeout_seconds: `str` The",
"protocol used doesn't support remote checks. Examples -------- # FileUtils >>> from pyats.utils.fileutils",
"... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size':",
"for NXOS device >>> fu_device = FileUtils.from_device(device) # copy file from device to",
"an issue Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate",
"*args, **kwargs): \"\"\" Rename a file Parameters ---------- source : `str` The URL",
"timeout_seconds : `int` Maximum allowed amount of time for the operation. Returns -------",
"---------- cmd (`str`): Command to be executed on the device target (`str`): File",
"from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: # For apidoc building only from",
"Parser encountered an issue Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils",
"unexpected behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instantiate",
"# FileUtils >>> from pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils instance for",
"from pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils instance for NXOS device >>>",
"allowed amount of time for the operation. Returns ------- `None` if operation succeeded.",
"before aborting the operation vrf: `str` Vrf to be used during copy operation",
"device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" # Extract device",
"cmd, *args, **kwargs): \"\"\" Rename a file Parameters ---------- source : `str` The",
": `int` Maximum allowed amount of time for the operation. Returns ------- `None`",
"to be used\") def copyconfiguration(self, source, destination, cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\"",
"Examples -------- # FileUtils >>> from pyats.utils.fileutils import FileUtils # Instantiate a filetransferutils",
"Logging import logging try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils",
"only list files at the top level of the given directory. Parameters ----------",
"**kwargs): \"\"\" Make sure that the given server information is valid Function that",
"destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file from server to device running configuration",
"device used_server: `str` Server address/name Returns ------- `None` Raises ------ Exception When a",
"operation. dir_output : `obj` The OS corresponding `dir` parser object Returns ------- `file_details`",
"... timeout_seconds=300, device=device) >>> directory_output['size'] ... '104260' >>> directory_output['permissions'] ... '-rw-' \"\"\" #",
"not passed in the function call Exception Parser encountered an issue Examples --------",
"parser obj = dir_output(device=device) parsed_output = obj.parse() return parsed_output def stat(self, target, timeout_seconds,",
"instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list the file details",
"command from the device to server is unreachable or the protocol used doesn't",
"device=device) \"\"\" logger.info('Verifying if server can be reached and if a temp file",
"*args, **kwargs): \"\"\" Delete a file Parameters ---------- target : `str` The URL",
"utils common base class \"\"\" # Logging import logging try: from pyats.utils.fileutils import",
"the function call Exception Parser encountered an issue Examples -------- # FileUtils >>>",
"directory 'flash:' >>> directory_output = fu_device.dir(target='flash:', ... timeout_seconds=300, device=device) >>> directory_output['dir']['flash:/']['files'] ... (Pdb)",
"the keyword arguments, if not passed raise an # AttributeError if 'device' in",
"... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs)",
"from the device to server is unreachable or the protocol used doesn't support",
"location destination: `str` Full path to the copy 'to' location timeout_seconds: `str` The",
"operation. dir_output : `obj` The OS corresponding `dir` parser object Returns ------- `dict`",
"destination : `str` The URL of the new file name. timeout_seconds : `int`",
"---------- target : `str` The URL of the file whose permissions are to",
"try: futlinux.deletefile(target) except Exception as e: raise type(e)(\"Server created file can't be deleted\")",
"cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination, timeout_seconds, cmd, *args,",
"fu_device.copyconfiguration( ... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration to device",
"to any location supported on the device and on the running-configuration. Parameters ----------",
"= FileUtils.from_device(device) # list the file details on the device 'flash:' directory >>>",
"corresponding `dir` parser object Returns ------- `file_details` : File details including size, permissions,",
"filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # delete a specific",
"fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl' ... timeout_seconds=300, device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def chmod(self, target, mode,",
"<reponame>wilbeacham85/genielibs<filename>pkgs/filetransferutils-pkg/src/genie/libs/filetransferutils/plugins/fileutils.py \"\"\" File utils common base class \"\"\" # Logging import logging try:",
"the running-configuration. Parameters ---------- source: `str` Full path to the copy 'from' location",
"def deletefile(self, target, timeout_seconds, *args, **kwargs): \"\"\" Delete a file Parameters ---------- target",
"device=device) \"\"\" # delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self,",
"and file location. timeout_seconds: `str` The number of seconds to wait before aborting",
"sure that the given server information is valid Function that verifies if the",
"any file to/from a device to any location supported on the device and",
"\\ filemode_to_mode except ImportError: # For apidoc building only from unittest.mock import Mock",
"dir_output : `obj` The OS corresponding `dir` parser object Returns ------- `dict` :",
"Returns ------- `file_details` : File details including size, permissions, index and last modified",
"device 'flash:' directory >>> directory_output = fu_device.stat(target='flash:memleak.tcl', ... timeout_seconds=300, device=device) >>> directory_output['size'] ...",
">>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl', ... timeout_seconds=300, device=device) \"\"\" # delete flash:memleak.tcl",
"can connect to it. It does this by saving `show clock` output to",
"It does this by saving `show clock` output to a particular file using",
"present or device execution encountered an unexpected behavior. Examples -------- # FileUtils >>>",
"checked\") from e # Delete server created file try: futlinux.deletefile(target) except Exception as",
"aborting the operation vrf: `str` Vrf to be used during copy operation Returns",
"file can ' 'be created') # Send the command try: self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, **kwargs)",
"device execution encountered an unexpected behavior. Examples -------- # FileUtils >>> from pyats.utils.fileutils",
"`None` Raises ------ Exception When a device object is not present or device",
"... timeout_seconds='300', device=device) # copy file from server to device >>> fu_device.copyfile( ...",
"The URL of the file whose permissions are to be changed. mode :",
"Instanciate a filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list",
"# filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: try: from pyats.utils.fileutils import",
"AttributeError if 'device' in kwargs: device = kwargs['device'] else: raise AttributeError(\"Device object is",
"# To be used when implemented # import stat as libstat # stat.filemode(output.st_mode)",
"running-configuration to device memory >>> fu_device.copyconfiguration( ... from_file_url='running-config', ... to_file_url='bootflash:filename', ... timeout_seconds='300', device=device)",
"Retrieve file details such as length and permissions. Parameters ---------- target : `str`",
"filetransferutils instance for NXOS device >>> fu_device = FileUtils.from_device(device) # list the file",
"path to the copy 'to' location timeout_seconds: `str` The number of seconds to",
"arguments, if not passed raise an # AttributeError if 'device' in kwargs: device",
"source: `str` Full path to the copy 'from' location destination: `str` Full path",
"a specific file on device directory 'flash:' >>> directory_output = fu_device.deletefile( ... target='flash:memleak_bckp.tcl',",
"succeeded. \"\"\" # To be used when implemented # import stat as libstat",
"the protocol used doesn't support remote checks. Examples -------- # FileUtils >>> from",
"# Extract device from the keyword arguments, if not passed raise an #",
"# delete flash:memleak.tcl cmd = 'delete {f}'.format(f=target) self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,**kwargs) def renamefile(self, source, destination,",
"and if a temp file can ' 'be created') # Send the command",
"... source='ftp://10.1.0.213//auto/tftp-ssr/config.py', ... destination='running-config', ... timeout_seconds='300', device=device) # copy running-configuration to device memory",
"raise an # AttributeError if 'device' in kwargs: device = kwargs['device'] else: raise",
"FileUtils >>> from pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils instance for NXOS",
"Call the parser obj = dir_output(device=device) parsed_output = obj.parse() return parsed_output def stat(self,",
"by saving `show clock` output to a particular file using transfer protocol. Then",
"aborting the operation. Default is 300 Returns ------- `None` Raises ------ Exception: If",
"timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server, **kwargs) def parsed_dir(self, target, timeout_seconds, dir_output, *args,",
"File details including size, permissions, index and last modified date. Raises ------ AttributeError",
"file to be renamed. destination : `str` The URL of the new file",
"device Copy any file to/from a device to any location supported on the",
"# delete a specific file on device directory 'flash:' >>> directory_output = fu_device.deletefile(",
"file can't be deleted\") from e # Great success! logger.info(\"Server is ready to",
"'size': '76', 'last_modified_date': 'Mar 20 2018 10:25:46 +00:00'} \"\"\" # Extract device from",
"seconds to wait before aborting the operation vrf: `str` Vrf to be used",
"Instantiate a filetransferutils instance for NXOS device >>> from pyats.utils.fileutils import FileUtils >>>",
"the parser obj = dir_output(device=device) parsed_output = obj.parse() return parsed_output def stat(self, target,",
"Copy a file to/from NXOS device Copy any file to/from a device to",
"and on the running-configuration. Parameters ---------- source: `str` Full path to the copy",
"if not passed raise an # AttributeError if 'device' not in kwargs: raise",
"supported on the device and on the server. Parameters ---------- source: `str` Full",
"try: from pyats.utils.fileutils import FileUtils as server # Server FileUtils core implementation #",
"Delete a file Parameters ---------- target : `str` The URL of the file",
"source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='flash:/new_file.tcl', ... timeout_seconds='300', device=device) # copy file from server to device",
"the copy 'to' location timeout_seconds: `str` The number of seconds to wait before",
"path to the copy 'from' location destination: `str` Full path to the copy",
"before aborting the operation cmd: `str` Command to be executed on the device",
"futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server created file can't be checked\") from",
"# AttributeError if 'device' not in kwargs: raise AttributeError(\"Devisce object is missing, can't",
"import FileUtils # Instantiate a filetransferutils instance for NXOS device >>> from pyats.utils.fileutils",
">>> fu_device.copyfile( ... source='ftp://10.1.0.213//auto/tftp-ssr/memleak.tcl', ... destination='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds, used_server=used_server,",
"not implement chmod.\".format(self.__module__)) def validateserver(self, cmd, target, timeout_seconds=300, *args, **kwargs): \"\"\" Make sure",
"(`str`): Command to be executed on the device target (`str`): File path including",
"running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ... timeout_seconds='300', device=device) \"\"\" self.send_cli_to_device(cli=cmd, timeout_seconds=timeout_seconds,",
"common base class \"\"\" # Logging import logging try: from pyats.utils.fileutils import FileUtils",
"device object is not present or device execution encountered an unexpected behavior. Examples",
"cmd, used_server, timeout_seconds=300, *args, **kwargs): \"\"\" Copy configuration to/from device Copy configuration on",
"timeout_seconds='300', device=device) # copy startup-configuration running-configuration >>> fu_device.copyconfiguration( ... from_file_url='startup-config', ... to_file_url='running-config', ...",
"kwargs['device'] else: raise AttributeError(\"Device object is missing, can't proceed with\" \" execution\") #",
"device to any location supported on the device and on the running-configuration. Parameters",
"# rename the file on the device 'flash:' directory >>> fu_device.renamefile(target='flash:memleak.tcl', ... destination='memleak_backup.tcl'",
"be deleted\") from e # Great success! logger.info(\"Server is ready to be used\")",
"# Check server created file try: futlinux.checkfile(target) except Exception as e: raise type(e)(\"Server",
"to be executed on the device used_server: `str` Server address/name Returns ------- `None`",
"in the function call Exception Parser encountered an issue Examples -------- # FileUtils",
"filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: # For apidoc building only",
"... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20 2018",
"used_server: `str` Server address/name Returns ------- `None` Raises ------ Exception When a device",
"on the device target (`str`): File path including the protocol, server and file",
"FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except ImportError: #",
"target='ftp://10.1.7.250//auto/tftp-ssr/show_clock', ... timeout_seconds=300, device=device) \"\"\" logger.info('Verifying if server can be reached and if",
"server(testbed=self.testbed) # Check server created file try: futlinux.checkfile(target) except Exception as e: raise",
"files at the top level of the given directory. Parameters ---------- target :",
"Default is 300 Returns ------- `None` Raises ------ Exception: If the command from",
"wait before aborting the operation cmd: `str` Command to be executed on the",
"instance for NXOS device >>> fu_device = FileUtils.from_device(device) # Validate server connectivity >>>",
"time for the operation. Returns ------- None Raises ------ Exception When a device",
"directory_output['dir']['flash:/']['files'] ... (Pdb) directory_output['dir']['flash:/']['files']['boothelper.log'] {'index': '69699', 'permissions': '-rw-', 'size': '76', 'last_modified_date': 'Mar 20",
"# Server FileUtils core implementation # filemode_to_mode from pyats.utils.fileutils.plugins.localhost.ftp.fileutils import \\ filemode_to_mode except",
"# import stat as libstat # stat.filemode(output.st_mode) # libstat.filemode(mode) raise NotImplementedError(\"The fileutils module",
"pyats.utils.fileutils import FileUtils # Instanciate a filetransferutils instance for NXOS device >>> fu_device",
"obj = dir_output(device=device) parsed_output = obj.parse() return parsed_output def stat(self, target, timeout_seconds, dir_output,",
"the given server information is valid Function that verifies if the server information",
"corresponding info (ex:size) Raises ------ AttributeError device object not passed in the function",
"in kwargs: raise AttributeError(\"Devisce object is missing, can't proceed with\" \" execution\") parsed_output",
"target (`str`): File path including the protocol, server and file location. timeout_seconds: `str`",
"the operation cmd: `str` Command to be executed on the device used_server: `str`"
] |
[
"patterns( '', # Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login',",
"django.conf.urls import patterns, url, include from django.contrib import admin from accounts import views",
"from accounts import views admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$',",
"from django.contrib import admin from accounts import views admin.autodiscover() urlpatterns = patterns( '',",
"admin from accounts import views admin.autodiscover() urlpatterns = patterns( '', # Examples: #",
"from django.conf.urls import patterns, url, include from django.contrib import admin from accounts import",
"'', # Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'),",
"# Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'), url(r'logout/$',",
"'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'), url(r'logout/$', views.logout_view, name='accounts-logout'), url(r'', include('registration.backends.default.urls')),",
"views admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$', 'worklogger.views.home', name='home'), #",
"# url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'), url(r'logout/$', views.logout_view, name='accounts-logout'),",
"<filename>accounts/urls.py from django.conf.urls import patterns, url, include from django.contrib import admin from accounts",
"patterns, url, include from django.contrib import admin from accounts import views admin.autodiscover() urlpatterns",
"name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'), url(r'logout/$', views.logout_view, name='accounts-logout'), url(r'', include('registration.backends.default.urls')), )",
"django.contrib import admin from accounts import views admin.autodiscover() urlpatterns = patterns( '', #",
"urlpatterns = patterns( '', # Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')),",
"import patterns, url, include from django.contrib import admin from accounts import views admin.autodiscover()",
"include from django.contrib import admin from accounts import views admin.autodiscover() urlpatterns = patterns(",
"url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'), url(r'logout/$', views.logout_view, name='accounts-logout'), url(r'',",
"admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/',",
"= patterns( '', # Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$',",
"import views admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$', 'worklogger.views.home', name='home'),",
"Examples: # url(r'^$', 'worklogger.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'login/$', 'django.contrib.auth.views.login', name='accounts-login'), url(r'logout/$', views.logout_view,",
"url, include from django.contrib import admin from accounts import views admin.autodiscover() urlpatterns =",
"accounts import views admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$', 'worklogger.views.home',",
"import admin from accounts import views admin.autodiscover() urlpatterns = patterns( '', # Examples:"
] |
[
"'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\",",
"OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except IndexError: continue",
"<filename>example/quality_to_dbm_short_example.py<gh_stars>1-10 \"\"\" retrieves signal quality from netsh.exe and converts it to rssi \"\"\"",
"-50 else: dbm = (quality / 2) - 100 dbm = int(dbm) print(\"quality,dbm\")",
"quality = int(value.replace(\"%\", \"\")) if quality <= 0: dbm = -100 elif quality",
"in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except IndexError:",
"1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\" in line:",
"quality >= 100: dbm = -50 else: dbm = (quality / 2) -",
"rssi \"\"\" import subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND)",
"if quality <= 0: dbm = -100 elif quality >= 100: dbm =",
"= ['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater",
"retrieves signal quality from netsh.exe and converts it to rssi \"\"\" import subprocess",
"it to rssi \"\"\" import subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT",
"dbm = (quality / 2) - 100 dbm = int(dbm) print(\"quality,dbm\") print(\"{},{}\".format(quality, dbm))",
"OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value",
"for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip()",
"= int(value.replace(\"%\", \"\")) if quality <= 0: dbm = -100 elif quality >=",
"COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines():",
"paramater = line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except IndexError: continue if",
"else: dbm = (quality / 2) - 100 dbm = int(dbm) print(\"quality,dbm\") print(\"{},{}\".format(quality,",
"int(value.replace(\"%\", \"\")) if quality <= 0: dbm = -100 elif quality >= 100:",
"signal quality from netsh.exe and converts it to rssi \"\"\" import subprocess COMMAND",
"from netsh.exe and converts it to rssi \"\"\" import subprocess COMMAND = ['netsh',",
"line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\" in",
"dbm = -100 elif quality >= 100: dbm = -50 else: dbm =",
"= line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\" in line: quality = int(value.replace(\"%\",",
"and converts it to rssi \"\"\" import subprocess COMMAND = ['netsh', 'wlan', 'show',",
"1)[1].strip() except IndexError: continue if \"signal\" in line: quality = int(value.replace(\"%\", \"\")) if",
"continue if \"signal\" in line: quality = int(value.replace(\"%\", \"\")) if quality <= 0:",
"quality from netsh.exe and converts it to rssi \"\"\" import subprocess COMMAND =",
"= -100 elif quality >= 100: dbm = -50 else: dbm = (quality",
"= -50 else: dbm = (quality / 2) - 100 dbm = int(dbm)",
"try: value = line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\" in line: quality",
"line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\" in line: quality = int(value.replace(\"%\", \"\"))",
"subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line in",
"in line: quality = int(value.replace(\"%\", \"\")) if quality <= 0: dbm = -100",
"quality <= 0: dbm = -100 elif quality >= 100: dbm = -50",
"\"signal\" in line: quality = int(value.replace(\"%\", \"\")) if quality <= 0: dbm =",
"import subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line",
"IndexError: continue if \"signal\" in line: quality = int(value.replace(\"%\", \"\")) if quality <=",
"= line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\"",
"except IndexError: continue if \"signal\" in line: quality = int(value.replace(\"%\", \"\")) if quality",
"'interface'] OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try:",
"['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater =",
"line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value = line.split(\":\", 1)[1].strip() except",
"\"\")) if quality <= 0: dbm = -100 elif quality >= 100: dbm",
"-100 elif quality >= 100: dbm = -50 else: dbm = (quality /",
"\"\"\" import subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT = subprocess.check_output(COMMAND) for",
"subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value = line.split(\":\",",
"'show', 'interface'] OUT = subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip()",
"line: quality = int(value.replace(\"%\", \"\")) if quality <= 0: dbm = -100 elif",
"dbm = -50 else: dbm = (quality / 2) - 100 dbm =",
"netsh.exe and converts it to rssi \"\"\" import subprocess COMMAND = ['netsh', 'wlan',",
"to rssi \"\"\" import subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface'] OUT =",
"elif quality >= 100: dbm = -50 else: dbm = (quality / 2)",
"0: dbm = -100 elif quality >= 100: dbm = -50 else: dbm",
">= 100: dbm = -50 else: dbm = (quality / 2) - 100",
"100: dbm = -50 else: dbm = (quality / 2) - 100 dbm",
"<= 0: dbm = -100 elif quality >= 100: dbm = -50 else:",
"if \"signal\" in line: quality = int(value.replace(\"%\", \"\")) if quality <= 0: dbm",
"value = line.split(\":\", 1)[1].strip() except IndexError: continue if \"signal\" in line: quality =",
"converts it to rssi \"\"\" import subprocess COMMAND = ['netsh', 'wlan', 'show', 'interface']",
"= subprocess.check_output(COMMAND) for line in OUT.decode(\"utf-8\").lower().splitlines(): paramater = line.split(\":\", 1)[0].strip() try: value =",
"\"\"\" retrieves signal quality from netsh.exe and converts it to rssi \"\"\" import"
] |
[
"benchmark_globals(): def sum_test(): return G_VAR + 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(),",
"2 def global_test(): return 1 def benchmark_globals(): def sum_test(): return G_VAR + 3",
"= 1 G_VAR2 = 2 def global_test(): return 1 def benchmark_globals(): def sum_test():",
"return G_VAR + 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) #",
") # locals = locals() # dir(locals) print(colored(f'{result} sec', 'green')) if __name__ ==",
"result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals = locals() #",
"return 1 def benchmark_globals(): def sum_test(): return G_VAR + 3 result = timeit.timeit(",
"import colored G_VAR = 1 G_VAR2 = 2 def global_test(): return 1 def",
"def global_test(): return 1 def benchmark_globals(): def sum_test(): return G_VAR + 3 result",
"globals=globals(), number=3 ) # locals = locals() # dir(locals) print(colored(f'{result} sec', 'green')) if",
"3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals = locals()",
"1 def benchmark_globals(): def sum_test(): return G_VAR + 3 result = timeit.timeit( setup='G_VAR2',",
"1 G_VAR2 = 2 def global_test(): return 1 def benchmark_globals(): def sum_test(): return",
"G_VAR = 1 G_VAR2 = 2 def global_test(): return 1 def benchmark_globals(): def",
"sum_test(): return G_VAR + 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 )",
"G_VAR2 = 2 def global_test(): return 1 def benchmark_globals(): def sum_test(): return G_VAR",
"number=3 ) # locals = locals() # dir(locals) print(colored(f'{result} sec', 'green')) if __name__",
"import timeit from termcolor import colored G_VAR = 1 G_VAR2 = 2 def",
"global_test(): return 1 def benchmark_globals(): def sum_test(): return G_VAR + 3 result =",
"def sum_test(): return G_VAR + 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3",
"stmt='global_test()', globals=globals(), number=3 ) # locals = locals() # dir(locals) print(colored(f'{result} sec', 'green'))",
"locals = locals() # dir(locals) print(colored(f'{result} sec', 'green')) if __name__ == '__main__': benchmark_globals()",
"def benchmark_globals(): def sum_test(): return G_VAR + 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()',",
"timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals = locals() # dir(locals) print(colored(f'{result}",
"colored G_VAR = 1 G_VAR2 = 2 def global_test(): return 1 def benchmark_globals():",
"termcolor import colored G_VAR = 1 G_VAR2 = 2 def global_test(): return 1",
"G_VAR + 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals",
"setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals = locals() # dir(locals) print(colored(f'{result} sec',",
"# locals = locals() # dir(locals) print(colored(f'{result} sec', 'green')) if __name__ == '__main__':",
"<reponame>sanghyunbak/effective_python<gh_stars>0 import timeit from termcolor import colored G_VAR = 1 G_VAR2 = 2",
"+ 3 result = timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals =",
"= timeit.timeit( setup='G_VAR2', stmt='global_test()', globals=globals(), number=3 ) # locals = locals() # dir(locals)",
"timeit from termcolor import colored G_VAR = 1 G_VAR2 = 2 def global_test():",
"= 2 def global_test(): return 1 def benchmark_globals(): def sum_test(): return G_VAR +",
"from termcolor import colored G_VAR = 1 G_VAR2 = 2 def global_test(): return"
] |
[
"current_app, json from freezegun import freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback,",
"app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import QueueNames from tests.conftest",
"x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\",",
"sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\",",
"= now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref,",
"sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is",
"mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api,",
"from freezegun import freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from",
"= datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery =",
"mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api,",
"create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\",",
") @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\",",
"(\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is",
"== some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\":",
"assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True,",
") @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\")",
"assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with",
"mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert len(mock_file_exists.mock_calls) ==",
"<= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback,",
"== ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with",
"datetime import datetime from unittest.mock import ANY, call import pytest import requests_mock from",
"mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] ==",
"def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}):",
"message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api,",
"None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload",
"mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref =",
"queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker):",
"phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now() timestamp",
"import datetime from unittest.mock import ANY, call import pytest import requests_mock from flask",
"import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import QueueNames from tests.conftest import",
") from app.config import QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher(",
"@freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as",
"request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25",
"content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def",
"= mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref)",
"filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\",",
"bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload",
"def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\")",
"region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True)",
") @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with",
"mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now()",
"set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert",
"sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import",
"def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post(",
"some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}):",
"queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery ==",
"with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api,",
"def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as",
"from unittest.mock import ANY, call import pytest import requests_mock from flask import current_app,",
"mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False)",
"14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker()",
"sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY,",
"14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError):",
"dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize(",
"mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE)",
"assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4())",
"def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\")",
"sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently",
"message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args)",
"flask import current_app, json from freezegun import freeze_time from app.aws.mocks import ( ses_notification_callback,",
"= mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\",",
"as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists",
"<gh_stars>10-100 import uuid from datetime import datetime from unittest.mock import ANY, call import",
"\"Phone carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number,",
"to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\",",
"14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\")",
"dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker):",
"import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response,",
"lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [",
"mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\",",
"mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\",",
"app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response,",
"is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ], )",
"(\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\":",
"unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\")",
"str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\")",
"return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request",
"= mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def",
"mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY,",
"timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref =",
"== sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\")",
"create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def",
"some_ref = str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref)",
"\"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref",
"str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api,",
"send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker):",
"mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\",",
"@freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with",
"@freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload =",
"False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher),",
"dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def",
"datetime from unittest.mock import ANY, call import pytest import requests_mock from flask import",
"now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery",
"as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher,",
"= mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message",
"requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker):",
"call import pytest import requests_mock from flask import current_app, json from freezegun import",
"mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls ==",
"= str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25",
"= json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False)",
"\"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\",",
"@pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback,",
"test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now =",
"x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\",",
"mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message =",
"mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert",
"mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert len(mock_file_exists.mock_calls) == 30 assert",
"@freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api,",
"%H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number,",
"requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"],",
"bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task =",
"ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from",
"\"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}),",
"freezegun import freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks",
"send_sms_response, ) from app.config import QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher =",
"14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock:",
"( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, )",
"unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task =",
"side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher),",
"region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task",
"test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert",
"True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\",",
"create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with(",
"mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4())",
"requests_mock from flask import current_app, json from freezegun import freeze_time from app.aws.mocks import",
"import freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import",
"assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload =",
"\"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] ==",
"test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock:",
"pytest import requests_mock from flask import current_app, json from freezegun import freeze_time from",
"{\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker,",
"phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\")",
"return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref)",
"@freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref =",
"unittest.mock import ANY, call import pytest import requests_mock from flask import current_app, json",
"request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, )",
"is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False])",
"{}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback,",
"= str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def",
"import ANY, call import pytest import requests_mock from flask import current_app, json from",
"from datetime import datetime from unittest.mock import ANY, call import pytest import requests_mock",
"[ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently",
") from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import QueueNames",
"datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0]",
"dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25",
"import current_app, json from freezegun import freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback,",
"def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now",
"send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\":",
"\"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\":",
"sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker):",
"status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api,",
"with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0])",
"with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None",
"assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY,",
"json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\")",
"sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d",
"now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\":",
"14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\":",
"= mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert len(mock_file_exists.mock_calls) == 30",
"mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False)",
"import uuid from datetime import datetime from unittest.mock import ANY, call import pytest",
"file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\")",
"tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x",
"mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists =",
"Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback,",
"from tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" <",
"mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery",
"uuid from datetime import datetime from unittest.mock import ANY, call import pytest import",
"\"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task =",
"with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"],",
"mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number,",
"call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\")",
"return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, )",
"set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25",
"send_email_response, send_sms_response, ) from app.config import QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher",
"request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists =",
"create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\",",
"file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload =",
"currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25",
"mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\")",
"sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now() timestamp =",
"currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task",
"ANY, call import pytest import requests_mock from flask import current_app, json from freezegun",
"from flask import current_app, json from freezegun import freeze_time from app.aws.mocks import (",
"freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import (",
"== [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY,",
"json from freezegun import freeze_time from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, )",
"import pytest import requests_mock from flask import current_app, json from freezegun import freeze_time",
"message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\",",
"mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\")",
"[ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher,",
"mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\",",
"filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\")",
"from app.config import QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\",",
"{}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier",
"is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args):",
"test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert",
"(\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}),",
"mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY,",
"mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\")",
"set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", )",
"mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200,",
"mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ]",
"test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mocker.patch(\"app.celery.research_mode_tasks.s3upload\") mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref",
"= Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number,",
"import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <=",
"app.config import QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda",
"sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config",
"{\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}),",
"\"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def",
"mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert len(mock_file_exists.mock_calls) == 30 assert not mock_s3upload.called",
"= str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY,",
"ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker()",
"call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, )",
"Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\",",
"from app.aws.mocks import ( ses_notification_callback, sns_failed_callback, sns_success_callback, ) from app.celery.research_mode_tasks import ( create_fake_letter_response_file,",
"test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\",",
"{\"NOTIFY_ENVIRONMENT\": \"development\"}): some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"]",
"< x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}),",
") create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_calls_dvla_callback_on_development(notify_api, mocker):",
"call(\"test.notify.com-ftp\", dvla_response_file_matcher), ] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api,",
"some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task",
"some_ref = str(uuid.uuid4()) create_fake_letter_response_file(some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message = json.loads(mock_task.apply_async.call_args[0][0][0]) assert message[\"MessageId\"] == some_ref",
"mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3]",
"], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\")",
"create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import QueueNames from tests.conftest import Matcher, set_config_values",
"sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api,",
"\"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with( filedata=\"random-ref|Sent|0|Sorted\", region=current_app.config[\"AWS_REGION\"], bucket_name=current_app.config[\"DVLA_RESPONSE_BUCKET_NAME\"], file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\")",
"mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with set_config_values(notify_api, {\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is",
"QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x: \"NOTIFY-20180125140000-RSP.TXT\"",
"\"NOTIFY-20180125140000-RSP.TXT\" < x <= \"NOTIFY-20180125140030-RSP.TXT\", ) @pytest.mark.parametrize( \"phone_number, sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback,",
"14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref = str(uuid.uuid4())",
"= mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [ call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher), call(\"test.notify.com-ftp\", dvla_response_file_matcher),",
"mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls",
"request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_tries_to_create_files_with_other_filenames(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True,",
"import requests_mock from flask import current_app, json from freezegun import freeze_time from app.aws.mocks",
"str(uuid.uuid4()) now = datetime.now() timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE)",
"phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp})",
"def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE)",
"mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert len(mock_file_exists.mock_calls)",
"message_celery == sns_callback(**sns_callback_args) def test_make_ses_callback(notify_api, mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref,",
"test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert",
"sns_callback, sns_callback_args\", [ (\"+15149301630\", sns_success_callback, {}), (\"+15149301631\", sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone",
"\"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ],",
"mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25",
"@freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists = mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with",
"( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import QueueNames from tests.conftest import Matcher,",
") @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback, sns_callback_args): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_sns_results\") some_ref",
"mocker): mock_task = mocker.patch(\"app.celery.research_mode_tasks.process_ses_results\") some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0]",
"{\"NOTIFY_ENVIRONMENT\": \"preview\"}): with requests_mock.Mocker() as request_mock: create_fake_letter_response_file(\"random-ref\") assert request_mock.last_request is None @freeze_time(\"2018-01-25 14:00:30\")",
"(\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def",
"= mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with requests_mock.Mocker() as request_mock: request_mock.post( \"http://localhost:6011/notifications/letter/dvla\", content=b\"{}\", status_code=200, ) create_fake_letter_response_file(\"random-ref\") mock_s3upload.assert_called_once_with(",
"return_value=True) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") with pytest.raises(ValueError): create_fake_letter_response_file(\"random-ref\") assert len(mock_file_exists.mock_calls) == 30 assert not",
"from app.celery.research_mode_tasks import ( create_fake_letter_response_file, send_email_response, send_sms_response, ) from app.config import QueueNames from",
"] mock_s3upload.assert_called_once_with( filedata=ANY, region=ANY, bucket_name=ANY, file_location=dvla_response_file_matcher, ) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_gives_up_after_thirty_times(notify_api, mocker): mock_file_exists",
"carrier is currently unreachable/unavailable\"}), ], ) @freeze_time(\"2018-01-25 14:00:30\") def test_make_sns_success_callback(notify_api, mocker, phone_number, sns_callback,",
"import QueueNames from tests.conftest import Matcher, set_config_values dvla_response_file_matcher = Matcher( \"dvla_response_file\", lambda x:",
"some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\": some_ref, \"destination\": phone_number, \"timestamp\": timestamp}) assert",
"sns_success_callback, {}), (\"+15149301632\", sns_failed_callback, {\"provider_response\": \"Phone is currently unreachable/unavailable\"}), (\"+15149301633\", sns_failed_callback, {\"provider_response\": \"Phone",
"= mocker.patch(\"app.celery.research_mode_tasks.file_exists\", side_effect=[True, True, False]) mock_s3upload = mocker.patch(\"app.celery.research_mode_tasks.s3upload\") create_fake_letter_response_file(\"random-ref\") assert mock_file_exists.mock_calls == [",
"some_ref = str(uuid.uuid4()) send_email_response(reference=some_ref, to=\"<EMAIL>\") mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\")",
"queue=QueueNames.RESEARCH_MODE) assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref) @freeze_time(\"2018-01-25 14:00:30\") def test_create_fake_letter_response_file_uploads_response_file_s3(notify_api, mocker): mocker.patch(\"app.celery.research_mode_tasks.file_exists\", return_value=False) mock_s3upload",
"timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3] send_sms_response(\"sns\", phone_number, some_ref) mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE) message_celery = mock_task.apply_async.call_args[0][0][0] sns_callback_args.update({\"reference\":"
] |
[
"typing import Any, List, Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str)",
"from subprocess import CalledProcessError, check_call, DEVNULL from typing import Any, List, Sequence import",
"APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed successfully\") return success def",
"from typing import Any, List, Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive:",
"can_handle(self, directive: str) -> bool: return directive == \"apt\" def handle(self, directive: str,",
"str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except CalledProcessError as",
"CalledProcessError, check_call, DEVNULL from typing import Any, List, Sequence import dotbot class Apt(dotbot.Plugin):",
"class Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool: return directive == \"apt\" def",
"packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed successfully\") return success def _run(self,",
"directive == \"apt\" def handle(self, directive: str, packages: List[str]) -> bool: success =",
"Any, List, Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool:",
"str, packages: List[str]) -> bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\",
"= self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] +",
"Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except",
"\"apt\" def handle(self, directive: str, packages: List[str]) -> bool: success = self._run([\"sudo\", \"apt\",",
"\"install\", \"-y\"] + packages, \"Installing the APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT",
"packages installed successfully\") return success def _run(self, command: Sequence[Any], low_info: str) -> bool:",
"return success def _run(self, command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command,",
"if success: self._log.info(\"APT packages installed successfully\") return success def _run(self, command: Sequence[Any], low_info:",
"directive: str) -> bool: return directive == \"apt\" def handle(self, directive: str, packages:",
"+ packages, \"Installing the APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed",
"the APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed successfully\") return success",
"handle(self, directive: str, packages: List[str]) -> bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating",
"import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool: return directive ==",
"successfully\") return success def _run(self, command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try:",
"-> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except CalledProcessError as e:",
"bool: return directive == \"apt\" def handle(self, directive: str, packages: List[str]) -> bool:",
"-> bool: return directive == \"apt\" def handle(self, directive: str, packages: List[str]) ->",
"\"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing the APT",
"low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except CalledProcessError",
"import Any, List, Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str) ->",
"\"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing",
"APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing the APT packages:",
"return directive == \"apt\" def handle(self, directive: str, packages: List[str]) -> bool: success",
"str) -> bool: return directive == \"apt\" def handle(self, directive: str, packages: List[str])",
"List, Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool: return",
"\"-y\"] + packages, \"Installing the APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages",
"check_call, DEVNULL from typing import Any, List, Sequence import dotbot class Apt(dotbot.Plugin): def",
"\"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing the",
"\\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing the APT packages: {}\".format(\",",
"{}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed successfully\") return success def _run(self, command:",
"installed successfully\") return success def _run(self, command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info)",
"dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool: return directive == \"apt\"",
"Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool: return directive",
"def _run(self, command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL)",
"\"apt\", \"install\", \"-y\"] + packages, \"Installing the APT packages: {}\".format(\", \".join(packages))) if success:",
"Apt(dotbot.Plugin): def can_handle(self, directive: str) -> bool: return directive == \"apt\" def handle(self,",
"\".join(packages))) if success: self._log.info(\"APT packages installed successfully\") return success def _run(self, command: Sequence[Any],",
"success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"]",
"bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except CalledProcessError as e: self._log.error(e)",
"and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing the APT packages: {}\".format(\", \".join(packages)))",
"bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\",",
"subprocess import CalledProcessError, check_call, DEVNULL from typing import Any, List, Sequence import dotbot",
"def handle(self, directive: str, packages: List[str]) -> bool: success = self._run([\"sudo\", \"apt\", \"update\"],",
"\"Installing the APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed successfully\") return",
"packages: List[str]) -> bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and",
"== \"apt\" def handle(self, directive: str, packages: List[str]) -> bool: success = self._run([\"sudo\",",
"self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages,",
"DEVNULL from typing import Any, List, Sequence import dotbot class Apt(dotbot.Plugin): def can_handle(self,",
"self._log.info(\"APT packages installed successfully\") return success def _run(self, command: Sequence[Any], low_info: str) ->",
"-> bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\", \"apt\",",
"self._run([\"sudo\", \"apt\", \"install\", \"-y\"] + packages, \"Installing the APT packages: {}\".format(\", \".join(packages))) if",
"import CalledProcessError, check_call, DEVNULL from typing import Any, List, Sequence import dotbot class",
"try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except CalledProcessError as e: self._log.error(e) return False",
"def can_handle(self, directive: str) -> bool: return directive == \"apt\" def handle(self, directive:",
"directive: str, packages: List[str]) -> bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\")",
"packages, \"Installing the APT packages: {}\".format(\", \".join(packages))) if success: self._log.info(\"APT packages installed successfully\")",
"self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True except CalledProcessError as e: self._log.error(e) return",
"success: self._log.info(\"APT packages installed successfully\") return success def _run(self, command: Sequence[Any], low_info: str)",
"_run(self, command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return",
"command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) return True",
"success def _run(self, command: Sequence[Any], low_info: str) -> bool: self._log.lowinfo(low_info) try: check_call(command, stdout=DEVNULL,",
"List[str]) -> bool: success = self._run([\"sudo\", \"apt\", \"update\"], \"Updating APT\") \\ and self._run([\"sudo\","
] |
[
"candidates: List[int] :type target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans = [] def",
"1, 2, 5, 6, 7, 10], 8)) # Don't know python data structure",
"0: return for i in range(work, len(candidates)): if i > work and candidates[i]",
"candidates.sort() self.ans = [] def help(work, candidates, target, path): if target == 0:",
"\"\"\" :type candidates: List[int] :type target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans =",
"for i in range(work, len(candidates)): if i > work and candidates[i] == candidates[i",
"len(candidates)): if i > work and candidates[i] == candidates[i - 1]: continue path.append(candidates[i])",
"return self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10], 8))",
"def help(work, candidates, target, path): if target == 0: self.ans.append(list(path)) return if target",
"\"\"\" candidates.sort() self.ans = [] def help(work, candidates, target, path): if target ==",
"candidates, target - candidates[i], path) path.pop() help(0, candidates, target, []) return self.ans solution",
"[] def help(work, candidates, target, path): if target == 0: self.ans.append(list(path)) return if",
"candidates, target, path): if target == 0: self.ans.append(list(path)) return if target < 0",
"target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans = [] def help(work, candidates, target,",
"8)) # Don't know python data structure well # 内部函数使用外部函数的变量如何解决: 使用类变量或者传参 # 注意去重的方法",
":type target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans = [] def help(work, candidates,",
"1, candidates, target - candidates[i], path) path.pop() help(0, candidates, target, []) return self.ans",
"<filename>CombinationSumII40.py<gh_stars>0 # encoding=utf8 class Solution: def combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int]",
"combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int] :type target: int :rtype: List[List[int]] \"\"\"",
"solution = Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10], 8)) # Don't",
"== 0: return for i in range(work, len(candidates)): if i > work and",
"# encoding=utf8 class Solution: def combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int] :type",
"def combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int] :type target: int :rtype: List[List[int]]",
"in range(work, len(candidates)): if i > work and candidates[i] == candidates[i - 1]:",
"candidates[i] == candidates[i - 1]: continue path.append(candidates[i]) help(i + 1, candidates, target -",
"> work and candidates[i] == candidates[i - 1]: continue path.append(candidates[i]) help(i + 1,",
"6, 7, 10], 8)) # Don't know python data structure well # 内部函数使用外部函数的变量如何解决:",
"+ 1, candidates, target - candidates[i], path) path.pop() help(0, candidates, target, []) return",
"[]) return self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10],",
"0 or len(candidates) == 0: return for i in range(work, len(candidates)): if i",
"work and candidates[i] == candidates[i - 1]: continue path.append(candidates[i]) help(i + 1, candidates,",
"target == 0: self.ans.append(list(path)) return if target < 0 or len(candidates) == 0:",
"target): \"\"\" :type candidates: List[int] :type target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans",
"or len(candidates) == 0: return for i in range(work, len(candidates)): if i >",
"path): if target == 0: self.ans.append(list(path)) return if target < 0 or len(candidates)",
":rtype: List[List[int]] \"\"\" candidates.sort() self.ans = [] def help(work, candidates, target, path): if",
"target, []) return self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7,",
"Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10], 8)) # Don't know python",
"print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10], 8)) # Don't know python data",
"Solution: def combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int] :type target: int :rtype:",
"path) path.pop() help(0, candidates, target, []) return self.ans solution = Solution() print(solution.combinationSum2([1, 1,",
"target, path): if target == 0: self.ans.append(list(path)) return if target < 0 or",
"help(0, candidates, target, []) return self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2, 5,",
"2, 5, 6, 7, 10], 8)) # Don't know python data structure well",
"return for i in range(work, len(candidates)): if i > work and candidates[i] ==",
"5, 6, 7, 10], 8)) # Don't know python data structure well #",
"7, 10], 8)) # Don't know python data structure well # 内部函数使用外部函数的变量如何解决: 使用类变量或者传参",
"and candidates[i] == candidates[i - 1]: continue path.append(candidates[i]) help(i + 1, candidates, target",
"- 1]: continue path.append(candidates[i]) help(i + 1, candidates, target - candidates[i], path) path.pop()",
"- candidates[i], path) path.pop() help(0, candidates, target, []) return self.ans solution = Solution()",
"10], 8)) # Don't know python data structure well # 内部函数使用外部函数的变量如何解决: 使用类变量或者传参 #",
"self.ans.append(list(path)) return if target < 0 or len(candidates) == 0: return for i",
"len(candidates) == 0: return for i in range(work, len(candidates)): if i > work",
"target < 0 or len(candidates) == 0: return for i in range(work, len(candidates)):",
"return if target < 0 or len(candidates) == 0: return for i in",
":type candidates: List[int] :type target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans = []",
"if i > work and candidates[i] == candidates[i - 1]: continue path.append(candidates[i]) help(i",
"candidates, target): \"\"\" :type candidates: List[int] :type target: int :rtype: List[List[int]] \"\"\" candidates.sort()",
"if target == 0: self.ans.append(list(path)) return if target < 0 or len(candidates) ==",
"path.append(candidates[i]) help(i + 1, candidates, target - candidates[i], path) path.pop() help(0, candidates, target,",
"0: self.ans.append(list(path)) return if target < 0 or len(candidates) == 0: return for",
"List[int] :type target: int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans = [] def help(work,",
"encoding=utf8 class Solution: def combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int] :type target:",
"candidates[i], path) path.pop() help(0, candidates, target, []) return self.ans solution = Solution() print(solution.combinationSum2([1,",
"self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10], 8)) #",
"class Solution: def combinationSum2(self, candidates, target): \"\"\" :type candidates: List[int] :type target: int",
"< 0 or len(candidates) == 0: return for i in range(work, len(candidates)): if",
"== 0: self.ans.append(list(path)) return if target < 0 or len(candidates) == 0: return",
"i in range(work, len(candidates)): if i > work and candidates[i] == candidates[i -",
"= [] def help(work, candidates, target, path): if target == 0: self.ans.append(list(path)) return",
"help(work, candidates, target, path): if target == 0: self.ans.append(list(path)) return if target <",
"if target < 0 or len(candidates) == 0: return for i in range(work,",
"= Solution() print(solution.combinationSum2([1, 1, 2, 5, 6, 7, 10], 8)) # Don't know",
"candidates[i - 1]: continue path.append(candidates[i]) help(i + 1, candidates, target - candidates[i], path)",
"help(i + 1, candidates, target - candidates[i], path) path.pop() help(0, candidates, target, [])",
"continue path.append(candidates[i]) help(i + 1, candidates, target - candidates[i], path) path.pop() help(0, candidates,",
"self.ans = [] def help(work, candidates, target, path): if target == 0: self.ans.append(list(path))",
"1]: continue path.append(candidates[i]) help(i + 1, candidates, target - candidates[i], path) path.pop() help(0,",
"i > work and candidates[i] == candidates[i - 1]: continue path.append(candidates[i]) help(i +",
"== candidates[i - 1]: continue path.append(candidates[i]) help(i + 1, candidates, target - candidates[i],",
"path.pop() help(0, candidates, target, []) return self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2,",
"candidates, target, []) return self.ans solution = Solution() print(solution.combinationSum2([1, 1, 2, 5, 6,",
"target - candidates[i], path) path.pop() help(0, candidates, target, []) return self.ans solution =",
"int :rtype: List[List[int]] \"\"\" candidates.sort() self.ans = [] def help(work, candidates, target, path):",
"range(work, len(candidates)): if i > work and candidates[i] == candidates[i - 1]: continue",
"List[List[int]] \"\"\" candidates.sort() self.ans = [] def help(work, candidates, target, path): if target"
] |
[] |
[
"== 4 or number == 13: state = 'UNLUCKY' elif number % 2",
"'UNLUCKY' elif number % 2 == 0: state = 'EVEN' else: state =",
"number == 4 or number == 13: state = 'UNLUCKY' elif number %",
"13: state = 'UNLUCKY' elif number % 2 == 0: state = 'EVEN'",
"elif number % 2 == 0: state = 'EVEN' else: state = 'ODD'",
"== 13: state = 'UNLUCKY' elif number % 2 == 0: state =",
"4 or number == 13: state = 'UNLUCKY' elif number % 2 ==",
"or number == 13: state = 'UNLUCKY' elif number % 2 == 0:",
"in range(1, 21): if number == 4 or number == 13: state =",
"number == 13: state = 'UNLUCKY' elif number % 2 == 0: state",
"state = 'UNLUCKY' elif number % 2 == 0: state = 'EVEN' else:",
"range(1, 21): if number == 4 or number == 13: state = 'UNLUCKY'",
"for number in range(1, 21): if number == 4 or number == 13:",
"% 2 == 0: state = 'EVEN' else: state = 'ODD' print(f'{number} is",
"number in range(1, 21): if number == 4 or number == 13: state",
"21): if number == 4 or number == 13: state = 'UNLUCKY' elif",
"if number == 4 or number == 13: state = 'UNLUCKY' elif number",
"number % 2 == 0: state = 'EVEN' else: state = 'ODD' print(f'{number}",
"2 == 0: state = 'EVEN' else: state = 'ODD' print(f'{number} is {state}!')",
"= 'UNLUCKY' elif number % 2 == 0: state = 'EVEN' else: state"
] |
[
"of this CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig. :rtype: str \"\"\" return",
"bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param bbox: The bbox of this",
"The bbox of this CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float] :param time_range:",
"The variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names is None:",
"The spatial_res of this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float :param bbox:",
"self._time_range = time_range @property def time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return:",
"# noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util class CubegenConfigCubeConfig(Model):",
"'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names = variable_names self._crs = crs",
"E501 \"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI :param variable_names: The variable_names of",
"value for `spatial_res`, must not be `None`\") # noqa: E501 self._spatial_res = spatial_res",
"List[str] :param crs: The crs of this CubegenConfigCubeConfig. # noqa: E501 :type crs:",
"bbox(self, bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param bbox: The bbox of",
"time_range of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range is None: raise",
"must not be `None`\") # noqa: E501 self._time_range = time_range @property def time_period(self):",
"of this CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period is None: raise ValueError(\"Invalid",
":rtype: List[date] \"\"\" return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range of",
"noqa: F401 from typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import",
"time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter def time_period(self, time_period):",
"bbox of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox is None: raise",
"this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\"",
"\"\"\" if time_range is None: raise ValueError(\"Invalid value for `time_range`, must not be",
"absolute_import from datetime import date, datetime # noqa: F401 from typing import List,",
"this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the",
":rtype: str \"\"\" return self._crs @crs.setter def crs(self, crs): \"\"\"Sets the crs of",
"import Model from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto",
"E501 self._time_range = time_range @property def time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig.",
"noqa: E501 self._time_range = time_range @property def time_period(self): \"\"\"Gets the time_period of this",
"return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param",
"value for `time_period`, must not be `None`\") # noqa: E501 self._time_period = time_period",
"= variable_names @property def crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig. :return: The",
"# noqa: E501 :type time_range: List[date] :param time_period: The time_period of this CubegenConfigCubeConfig.",
"'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names = variable_names",
"of this CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return",
"def time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return: The time_range of this",
"time_range(self, time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param time_range: The time_range of",
"\"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this CubegenConfigCubeConfig.",
"variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names is None: raise",
"of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names is None: raise ValueError(\"Invalid",
"the spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type",
"The time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter def time_range(self,",
"None: raise ValueError(\"Invalid value for `spatial_res`, must not be `None`\") # noqa: E501",
"this CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names",
"@time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param time_range: The",
"CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range",
"def time_period(self, time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param time_period: The time_period",
"raise ValueError(\"Invalid value for `bbox`, must not be `None`\") # noqa: E501 self._bbox",
"CubegenConfigCubeConfig. # noqa: E501 :type crs: str :param spatial_res: The spatial_res of this",
"of this CubegenConfigCubeConfig. :type crs: str \"\"\" if crs is None: raise ValueError(\"Invalid",
"from typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from",
"} self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range':",
"of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res is None: raise ValueError(\"Invalid",
"CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self):",
"bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter def bbox(self, bbox):",
"if variable_names is None: raise ValueError(\"Invalid value for `variable_names`, must not be `None`\")",
"# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime #",
"of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range is None: raise ValueError(\"Invalid",
"crs: str :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. # noqa: E501 :type",
"time_period of this CubegenConfigCubeConfig. # noqa: E501 :type time_period: str \"\"\" self.openapi_types =",
"is None: raise ValueError(\"Invalid value for `variable_names`, must not be `None`\") # noqa:",
"\"\"\" return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig.",
"bbox: List[float] \"\"\" if bbox is None: raise ValueError(\"Invalid value for `bbox`, must",
"The time_period of this CubegenConfigCubeConfig. # noqa: E501 :type time_period: str \"\"\" self.openapi_types",
"dict. :type: dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501 :rtype:",
"None: raise ValueError(\"Invalid value for `crs`, must not be `None`\") # noqa: E501",
"value for `bbox`, must not be `None`\") # noqa: E501 self._bbox = bbox",
"time_range is None: raise ValueError(\"Invalid value for `time_range`, must not be `None`\") #",
"of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float",
"The spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res is None:",
"spatial_res @property def bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return: The bbox",
"not be `None`\") # noqa: E501 self._time_range = time_range @property def time_period(self): \"\"\"Gets",
"return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param",
"the bbox of this CubegenConfigCubeConfig. :param bbox: The bbox of this CubegenConfigCubeConfig. :type",
"this CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range",
"CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls)",
"datetime # noqa: F401 from typing import List, Dict # noqa: F401 from",
"def bbox(self, bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param bbox: The bbox",
"E501 :type time_range: List[date] :param time_period: The time_period of this CubegenConfigCubeConfig. # noqa:",
"the time_period of this CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig. :rtype: str",
"variable_names of this CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str] :param crs: The",
"of this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float :param bbox: The bbox",
"for `variable_names`, must not be `None`\") # noqa: E501 self._variable_names = variable_names @property",
"CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names",
"List[float] \"\"\" if bbox is None: raise ValueError(\"Invalid value for `bbox`, must not",
"# noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets",
"this CubegenConfigCubeConfig. :param time_range: The time_range of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\"",
"def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res",
"bbox self._time_range = time_range self._time_period = time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig':",
"time_period of this CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\"",
"\"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig. :rtype:",
"CubegenConfigCubeConfig. :param crs: The crs of this CubegenConfigCubeConfig. :type crs: str \"\"\" if",
"self._spatial_res = spatial_res self._bbox = bbox self._time_range = time_range self._time_period = time_period @classmethod",
"-> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model :param dikt: A dict. :type:",
"the time_period of this CubegenConfigCubeConfig. :param time_period: The time_period of this CubegenConfigCubeConfig. :type",
"must not be `None`\") # noqa: E501 self._spatial_res = spatial_res @property def bbox(self):",
"None: raise ValueError(\"Invalid value for `bbox`, must not be `None`\") # noqa: E501",
"if time_period is None: raise ValueError(\"Invalid value for `time_period`, must not be `None`\")",
"time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI :param",
"of this CubegenConfigCubeConfig. # noqa: E501 :type crs: str :param spatial_res: The spatial_res",
"self._crs = crs self._spatial_res = spatial_res self._bbox = bbox self._time_range = time_range self._time_period",
"# noqa: E501 self._bbox = bbox @property def time_range(self): \"\"\"Gets the time_range of",
"time_range self._time_period = time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict",
"from xcube_hub.models.base_model_ import Model from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class",
"@property def spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res of",
"of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox is None: raise ValueError(\"Invalid",
"time_period(self, time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param time_period: The time_period of",
"return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param",
"CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter",
"float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this",
"time_range: List[date] :param time_period: The time_period of this CubegenConfigCubeConfig. # noqa: E501 :type",
"Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util class",
"from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model :param dikt: A",
"ValueError(\"Invalid value for `crs`, must not be `None`\") # noqa: E501 self._crs =",
"model :param dikt: A dict. :type: dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig.",
"def time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return: The time_period of this",
"util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).",
"for `crs`, must not be `None`\") # noqa: E501 self._crs = crs @property",
":type crs: str :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. # noqa: E501",
"= bbox self._time_range = time_range self._time_period = time_period @classmethod def from_dict(cls, dikt) ->",
"CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range is None: raise ValueError(\"Invalid value for",
"List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util",
"noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI :param variable_names: The variable_names",
"List[str] \"\"\" if variable_names is None: raise ValueError(\"Invalid value for `variable_names`, must not",
"def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model :param dikt:",
"value for `variable_names`, must not be `None`\") # noqa: E501 self._variable_names = variable_names",
"`None`\") # noqa: E501 self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets the bbox",
"`None`\") # noqa: E501 self._bbox = bbox @property def time_range(self): \"\"\"Gets the time_range",
":rtype: float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of",
"crs of this CubegenConfigCubeConfig. :type crs: str \"\"\" if crs is None: raise",
"this CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox",
"import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated by OpenAPI Generator",
"of this CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date] :param time_period: The time_period",
"def spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res of this",
"if bbox is None: raise ValueError(\"Invalid value for `bbox`, must not be `None`\")",
"str \"\"\" if time_period is None: raise ValueError(\"Invalid value for `time_period`, must not",
"List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names of this",
"CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date] :param time_period: The time_period of this",
"The time_range of this CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date] :param time_period:",
"time_period: str \"\"\" self.openapi_types = { 'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox':",
"time_range @property def time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return: The time_period",
"variable_names @property def crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig. :return: The crs",
"raise ValueError(\"Invalid value for `crs`, must not be `None`\") # noqa: E501 self._crs",
"is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually.",
"self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param variable_names:",
"if crs is None: raise ValueError(\"Invalid value for `crs`, must not be `None`\")",
"\"\"\" return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig.",
"this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox is None: raise ValueError(\"Invalid value",
"typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub",
"CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox is None: raise ValueError(\"Invalid value for",
":return: The time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter def",
"of this CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float] :param time_range: The time_range",
"this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float :param bbox: The bbox of",
"str \"\"\" if crs is None: raise ValueError(\"Invalid value for `crs`, must not",
"datetime import date, datetime # noqa: F401 from typing import List, Dict #",
"be `None`\") # noqa: E501 self._variable_names = variable_names @property def crs(self): \"\"\"Gets the",
"of this CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\" return",
"CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if",
"\"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param bbox: The bbox of this CubegenConfigCubeConfig.",
"not edit the class manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None,",
"= crs @property def spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return: The",
"The bbox of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox is None:",
"A dict. :type: dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501",
"crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig. :param crs: The crs of this",
"time_period of this CubegenConfigCubeConfig. :param time_period: The time_period of this CubegenConfigCubeConfig. :type time_period:",
":type variable_names: List[str] :param crs: The crs of this CubegenConfigCubeConfig. # noqa: E501",
"return self._crs @crs.setter def crs(self, crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig. :param",
"not be `None`\") # noqa: E501 self._bbox = bbox @property def time_range(self): \"\"\"Gets",
"The crs of this CubegenConfigCubeConfig. :type crs: str \"\"\" if crs is None:",
"noqa: E501 :type spatial_res: float :param bbox: The bbox of this CubegenConfigCubeConfig. #",
"this CubegenConfigCubeConfig. # noqa: E501 :type time_period: str \"\"\" self.openapi_types = { 'variable_names':",
"CubegenConfigCubeConfig. :param time_range: The time_range of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if",
"manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501",
"'bbox': List[float], 'time_range': List[date], 'time_period': str } self.attribute_map = { 'variable_names': 'variable_names', 'crs':",
"CubegenConfigCubeConfig. :param time_period: The time_period of this CubegenConfigCubeConfig. :type time_period: str \"\"\" if",
"- a model defined in OpenAPI :param variable_names: The variable_names of this CubegenConfigCubeConfig.",
"The spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self,",
"time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI :param variable_names:",
"time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig.",
"noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the",
"variable_names of this CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\"",
"edit the class manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None):",
"the crs of this CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig. :rtype: str",
"spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined in",
"time_period: The time_period of this CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period is",
"noqa: E501 self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets the bbox of this",
"self._variable_names = variable_names @property def crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig. :return:",
"The time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter def time_period(self,",
"noqa: E501 :type variable_names: List[str] :param crs: The crs of this CubegenConfigCubeConfig. #",
"bbox of this CubegenConfigCubeConfig. :param bbox: The bbox of this CubegenConfigCubeConfig. :type bbox:",
":type bbox: List[float] \"\"\" if bbox is None: raise ValueError(\"Invalid value for `bbox`,",
"raise ValueError(\"Invalid value for `spatial_res`, must not be `None`\") # noqa: E501 self._spatial_res",
"`crs`, must not be `None`\") # noqa: E501 self._crs = crs @property def",
"spatial_res: float :param bbox: The bbox of this CubegenConfigCubeConfig. # noqa: E501 :type",
"The bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter def bbox(self,",
"this CubegenConfigCubeConfig. # noqa: E501 :type crs: str :param spatial_res: The spatial_res of",
"this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the",
"\"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig.",
"variable_names: The variable_names of this CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str] :param",
"\"\"\" if bbox is None: raise ValueError(\"Invalid value for `bbox`, must not be",
"the dict as a model :param dikt: A dict. :type: dict :return: The",
"\"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param time_period: The time_period of this CubegenConfigCubeConfig.",
"crs of this CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig. :rtype: str \"\"\"",
"@property def variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return: The variable_names of",
"this CubegenConfigCubeConfig. :param variable_names: The variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\"",
"float \"\"\" if spatial_res is None: raise ValueError(\"Invalid value for `spatial_res`, must not",
"E501 self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig.",
"time_period: The time_period of this CubegenConfigCubeConfig. # noqa: E501 :type time_period: str \"\"\"",
"\"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig. :rtype:",
":type bbox: List[float] :param time_range: The time_range of this CubegenConfigCubeConfig. # noqa: E501",
"E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the variable_names",
":type spatial_res: float :param bbox: The bbox of this CubegenConfigCubeConfig. # noqa: E501",
"import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import",
"The time_range of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range is None:",
"= variable_names self._crs = crs self._spatial_res = spatial_res self._bbox = bbox self._time_range =",
"must not be `None`\") # noqa: E501 self._crs = crs @property def spatial_res(self):",
"noqa: E501 self._bbox = bbox @property def time_range(self): \"\"\"Gets the time_range of this",
"crs of this CubegenConfigCubeConfig. :param crs: The crs of this CubegenConfigCubeConfig. :type crs:",
"a model defined in OpenAPI :param variable_names: The variable_names of this CubegenConfigCubeConfig. #",
"\"\"\" if variable_names is None: raise ValueError(\"Invalid value for `variable_names`, must not be",
"this CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period is None: raise ValueError(\"Invalid value",
"'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' }",
"of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets",
"date, datetime # noqa: F401 from typing import List, Dict # noqa: F401",
"{ 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period'",
"@spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The",
"@classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model :param",
"in OpenAPI :param variable_names: The variable_names of this CubegenConfigCubeConfig. # noqa: E501 :type",
"'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names = variable_names self._crs =",
"The crs of this CubegenConfigCubeConfig. # noqa: E501 :type crs: str :param spatial_res:",
"= crs self._spatial_res = spatial_res self._bbox = bbox self._time_range = time_range self._time_period =",
":param crs: The crs of this CubegenConfigCubeConfig. # noqa: E501 :type crs: str",
"noqa: E501 :type time_range: List[date] :param time_period: The time_period of this CubegenConfigCubeConfig. #",
"def bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return: The bbox of this",
"variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names):",
"spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res is",
"of this CubegenConfigCubeConfig. :param bbox: The bbox of this CubegenConfigCubeConfig. :type bbox: List[float]",
"this CubegenConfigCubeConfig. :type crs: str \"\"\" if crs is None: raise ValueError(\"Invalid value",
"E501 :type spatial_res: float :param bbox: The bbox of this CubegenConfigCubeConfig. # noqa:",
"float, 'bbox': List[float], 'time_range': List[date], 'time_period': str } self.attribute_map = { 'variable_names': 'variable_names',",
":param time_range: The time_range of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range",
"self._variable_names = variable_names self._crs = crs self._spatial_res = spatial_res self._bbox = bbox self._time_range",
"is None: raise ValueError(\"Invalid value for `spatial_res`, must not be `None`\") # noqa:",
":return: The bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter def",
"bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI",
"'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names =",
"'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names = variable_names self._crs",
"@property def crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig. :return: The crs of",
"raise ValueError(\"Invalid value for `time_range`, must not be `None`\") # noqa: E501 self._time_range",
"value for `crs`, must not be `None`\") # noqa: E501 self._crs = crs",
"@variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param variable_names: The",
"__init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a",
"of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets",
"time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param time_range: The time_range of this",
"variable_names(self, variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param variable_names: The variable_names of",
"# noqa: E501 :type time_period: str \"\"\" self.openapi_types = { 'variable_names': List[str], 'crs':",
"is None: raise ValueError(\"Invalid value for `crs`, must not be `None`\") # noqa:",
"List[date] \"\"\" return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range of this",
"for `bbox`, must not be `None`\") # noqa: E501 self._bbox = bbox @property",
"spatial_res self._bbox = bbox self._time_range = time_range self._time_period = time_period @classmethod def from_dict(cls,",
":return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return",
"\"\"\" if spatial_res is None: raise ValueError(\"Invalid value for `spatial_res`, must not be",
"crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined",
"@property def time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return: The time_range of",
"'time_range': List[date], 'time_period': str } self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res':",
"= time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a",
"\"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit",
"List[float] \"\"\" return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox of this",
"= spatial_res self._bbox = bbox self._time_range = time_range self._time_period = time_period @classmethod def",
"str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period': str } self.attribute_map = {",
"'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names",
"self._crs @crs.setter def crs(self, crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig. :param crs:",
"\"\"\" return self._crs @crs.setter def crs(self, crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig.",
"noqa: E501 self._crs = crs @property def spatial_res(self): \"\"\"Gets the spatial_res of this",
"crs of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter def crs(self, crs):",
"E501 self._variable_names = variable_names @property def crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig.",
"this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the",
"this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range is None: raise ValueError(\"Invalid value",
"`None`\") # noqa: E501 self._crs = crs @property def spatial_res(self): \"\"\"Gets the spatial_res",
"CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res",
"be `None`\") # noqa: E501 self._crs = crs @property def spatial_res(self): \"\"\"Gets the",
"CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res is None: raise ValueError(\"Invalid value for",
"ValueError(\"Invalid value for `time_range`, must not be `None`\") # noqa: E501 self._time_range =",
"'time_period': 'time_period' } self._variable_names = variable_names self._crs = crs self._spatial_res = spatial_res self._bbox",
":type time_range: List[date] \"\"\" if time_range is None: raise ValueError(\"Invalid value for `time_range`,",
"CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter def crs(self, crs): \"\"\"Sets the crs",
"crs: The crs of this CubegenConfigCubeConfig. # noqa: E501 :type crs: str :param",
"def variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return: The variable_names of this",
"time_range: List[date] \"\"\" if time_range is None: raise ValueError(\"Invalid value for `time_range`, must",
"crs is None: raise ValueError(\"Invalid value for `crs`, must not be `None`\") #",
":param variable_names: The variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names",
"this CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date] :param time_period: The time_period of",
"noqa: E501 :type time_period: str \"\"\" self.openapi_types = { 'variable_names': List[str], 'crs': str,",
":type time_period: str \"\"\" self.openapi_types = { 'variable_names': List[str], 'crs': str, 'spatial_res': float,",
"def variable_names(self, variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param variable_names: The variable_names",
"ValueError(\"Invalid value for `bbox`, must not be `None`\") # noqa: E501 self._bbox =",
"be `None`\") # noqa: E501 self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets the",
"OpenAPI :param variable_names: The variable_names of this CubegenConfigCubeConfig. # noqa: E501 :type variable_names:",
"bbox: The bbox of this CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float] :param",
"= { 'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period':",
"noqa: E501 :type crs: str :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. #",
"this CubegenConfigCubeConfig. :param time_period: The time_period of this CubegenConfigCubeConfig. :type time_period: str \"\"\"",
"variable_names: List[str] \"\"\" if variable_names is None: raise ValueError(\"Invalid value for `variable_names`, must",
"time_range: The time_range of this CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date] :param",
"self._crs = crs @property def spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return:",
"this CubegenConfigCubeConfig. :param bbox: The bbox of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\"",
"`spatial_res`, must not be `None`\") # noqa: E501 self._spatial_res = spatial_res @property def",
"is None: raise ValueError(\"Invalid value for `time_period`, must not be `None`\") # noqa:",
"CubegenConfigCubeConfig. :param bbox: The bbox of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if",
"not be `None`\") # noqa: E501 self._variable_names = variable_names @property def crs(self): \"\"\"Gets",
"noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE:",
"model defined in OpenAPI :param variable_names: The variable_names of this CubegenConfigCubeConfig. # noqa:",
"the bbox of this CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig. :rtype: List[float]",
"str \"\"\" return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period of this",
"CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the variable_names of this",
"not be `None`\") # noqa: E501 self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets",
"the time_range of this CubegenConfigCubeConfig. :param time_range: The time_range of this CubegenConfigCubeConfig. :type",
"ValueError(\"Invalid value for `spatial_res`, must not be `None`\") # noqa: E501 self._spatial_res =",
"of this CubegenConfigCubeConfig. :param time_period: The time_period of this CubegenConfigCubeConfig. :type time_period: str",
"this CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs",
"crs(self, crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig. :param crs: The crs of",
"\"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param time_range: The time_range of this CubegenConfigCubeConfig.",
"`None`\") # noqa: E501 self._time_range = time_range @property def time_period(self): \"\"\"Gets the time_period",
"(https://openapi-generator.tech). Do not edit the class manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None,",
"dikt: A dict. :type: dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa:",
"the variable_names of this CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig. :rtype: List[str]",
"def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig -",
"return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return:",
"def crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig. :return: The crs of this",
"'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model :param dikt: A dict. :type: dict",
"for `time_range`, must not be `None`\") # noqa: E501 self._time_range = time_range @property",
"import date, datetime # noqa: F401 from typing import List, Dict # noqa:",
"return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param",
"@time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param time_period: The",
"The time_period of this CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period is None:",
"crs: str \"\"\" if crs is None: raise ValueError(\"Invalid value for `crs`, must",
"Model from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated",
"'time_range', 'time_period': 'time_period' } self._variable_names = variable_names self._crs = crs self._spatial_res = spatial_res",
"str } self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox',",
"crs(self): \"\"\"Gets the crs of this CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig.",
"self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param time_period:",
"bbox: The bbox of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox is",
"CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter",
"of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter def crs(self, crs): \"\"\"Sets",
"List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period': str } self.attribute_map",
"E501 self._crs = crs @property def spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig.",
"of this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets",
"if spatial_res is None: raise ValueError(\"Invalid value for `spatial_res`, must not be `None`\")",
"of this CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str] :param crs: The crs",
":rtype: str \"\"\" return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period of",
"E501 :type time_period: str \"\"\" self.openapi_types = { 'variable_names': List[str], 'crs': str, 'spatial_res':",
"ValueError(\"Invalid value for `time_period`, must not be `None`\") # noqa: E501 self._time_period =",
"of this CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return",
"variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig - a model",
"\"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig. :rtype:",
"time_range of this CubegenConfigCubeConfig. :param time_range: The time_range of this CubegenConfigCubeConfig. :type time_range:",
"\"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param variable_names: The variable_names of this CubegenConfigCubeConfig.",
"'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names = variable_names self._crs = crs self._spatial_res =",
"# noqa: E501 \"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI :param variable_names: The",
"of this CubegenConfigCubeConfig. # noqa: E501 :type time_period: str \"\"\" self.openapi_types = {",
"None: raise ValueError(\"Invalid value for `variable_names`, must not be `None`\") # noqa: E501",
":param spatial_res: The spatial_res of this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float",
"not be `None`\") # noqa: E501 self._crs = crs @property def spatial_res(self): \"\"\"Gets",
"noqa: E501 self._variable_names = variable_names @property def crs(self): \"\"\"Gets the crs of this",
"self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return:",
"E501 :type variable_names: List[str] :param crs: The crs of this CubegenConfigCubeConfig. # noqa:",
":type: dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig",
"for `spatial_res`, must not be `None`\") # noqa: E501 self._spatial_res = spatial_res @property",
"this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res is None: raise ValueError(\"Invalid value",
"\"\"\"Returns the dict as a model :param dikt: A dict. :type: dict :return:",
"E501 self._bbox = bbox @property def time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig.",
"'time_period': str } self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox':",
"variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig. :param variable_names: The variable_names of this",
"str \"\"\" return self._crs @crs.setter def crs(self, crs): \"\"\"Sets the crs of this",
"this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the",
"of this CubegenConfigCubeConfig. :param time_range: The time_range of this CubegenConfigCubeConfig. :type time_range: List[date]",
"be `None`\") # noqa: E501 self._time_range = time_range @property def time_period(self): \"\"\"Gets the",
"bbox of this CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float] :param time_range: The",
"{ 'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period': str",
"this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def",
"this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the",
"noqa: E501 :type bbox: List[float] :param time_range: The time_range of this CubegenConfigCubeConfig. #",
"CubegenConfigCubeConfig. :param variable_names: The variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if",
"The crs of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter def crs(self,",
"import absolute_import from datetime import date, datetime # noqa: F401 from typing import",
"\"\"\"Sets the crs of this CubegenConfigCubeConfig. :param crs: The crs of this CubegenConfigCubeConfig.",
"spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type spatial_res:",
"bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig.",
"List[date] \"\"\" if time_range is None: raise ValueError(\"Invalid value for `time_range`, must not",
"raise ValueError(\"Invalid value for `variable_names`, must not be `None`\") # noqa: E501 self._variable_names",
"= { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range', 'time_period':",
"= time_range @property def time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return: The",
":type crs: str \"\"\" if crs is None: raise ValueError(\"Invalid value for `crs`,",
"# noqa: E501 self._variable_names = variable_names @property def crs(self): \"\"\"Gets the crs of",
"Do not edit the class manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None,",
"# noqa: E501 self._crs = crs @property def spatial_res(self): \"\"\"Gets the spatial_res of",
"'bbox', 'time_range': 'time_range', 'time_period': 'time_period' } self._variable_names = variable_names self._crs = crs self._spatial_res",
"= bbox @property def time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return: The",
"variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig.",
"of this CubegenConfigCubeConfig. :param crs: The crs of this CubegenConfigCubeConfig. :type crs: str",
"bbox @property def time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return: The time_range",
"\"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa: E501 \"\"\"CubegenConfigCubeConfig",
"this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter def crs(self, crs): \"\"\"Sets the",
"class manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): # noqa:",
"CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter",
":return: The spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter def",
"auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. \"\"\"",
"'time_period' } self._variable_names = variable_names self._crs = crs self._spatial_res = spatial_res self._bbox =",
":param time_period: The time_period of this CubegenConfigCubeConfig. # noqa: E501 :type time_period: str",
":rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names of",
"crs of this CubegenConfigCubeConfig. # noqa: E501 :type crs: str :param spatial_res: The",
"__future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing",
"float :param bbox: The bbox of this CubegenConfigCubeConfig. # noqa: E501 :type bbox:",
"variable_names of this CubegenConfigCubeConfig. :param variable_names: The variable_names of this CubegenConfigCubeConfig. :type variable_names:",
"CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str] :param crs: The crs of this",
"must not be `None`\") # noqa: E501 self._variable_names = variable_names @property def crs(self):",
"None: raise ValueError(\"Invalid value for `time_range`, must not be `None`\") # noqa: E501",
"@property def bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return: The bbox of",
"from datetime import date, datetime # noqa: F401 from typing import List, Dict",
"OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. \"\"\" def __init__(self, variable_names=None,",
"class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do",
"List[date] :param time_period: The time_period of this CubegenConfigCubeConfig. # noqa: E501 :type time_period:",
"bbox: List[float] :param time_range: The time_range of this CubegenConfigCubeConfig. # noqa: E501 :type",
"value for `time_range`, must not be `None`\") # noqa: E501 self._time_range = time_range",
"spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res):",
"time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig.",
"spatial_res: float \"\"\" if spatial_res is None: raise ValueError(\"Invalid value for `spatial_res`, must",
"str :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res:",
"@crs.setter def crs(self, crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig. :param crs: The",
"CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float :param bbox: The bbox of this",
"def crs(self, crs): \"\"\"Sets the crs of this CubegenConfigCubeConfig. :param crs: The crs",
"\"\"\" return self._variable_names @variable_names.setter def variable_names(self, variable_names): \"\"\"Sets the variable_names of this CubegenConfigCubeConfig.",
"The variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def variable_names(self,",
"\"\"\" if crs is None: raise ValueError(\"Invalid value for `crs`, must not be",
"# noqa: E501 self._spatial_res = spatial_res @property def bbox(self): \"\"\"Gets the bbox of",
"E501 :type crs: str :param spatial_res: The spatial_res of this CubegenConfigCubeConfig. # noqa:",
"bbox of this CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\"",
"utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401",
":param time_period: The time_period of this CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period",
":rtype: List[float] \"\"\" return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox of",
"self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param bbox:",
":type time_range: List[date] :param time_period: The time_period of this CubegenConfigCubeConfig. # noqa: E501",
"return self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param",
"# noqa: E501 :type bbox: List[float] :param time_range: The time_range of this CubegenConfigCubeConfig.",
"<gh_stars>1-10 # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime",
"crs: The crs of this CubegenConfigCubeConfig. :type crs: str \"\"\" if crs is",
"spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\"",
":param spatial_res: The spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res",
"'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period': str } self.attribute_map = { 'variable_names':",
"spatial_res of this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float :param bbox: The",
"the variable_names of this CubegenConfigCubeConfig. :param variable_names: The variable_names of this CubegenConfigCubeConfig. :type",
"this CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig. :rtype: float \"\"\" return self._spatial_res",
"dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model :param dikt: A dict.",
"List[date], 'time_period': str } self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res',",
"generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. \"\"\" def",
"this CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period",
"of this CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return",
"crs @property def spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res",
"\"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig.",
"must not be `None`\") # noqa: E501 self._bbox = bbox @property def time_range(self):",
"self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param time_range:",
"dict as a model :param dikt: A dict. :type: dict :return: The CubegenConfig_cube_config",
"None: raise ValueError(\"Invalid value for `time_period`, must not be `None`\") # noqa: E501",
"the spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig. :rtype: float",
"The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt,",
"the crs of this CubegenConfigCubeConfig. :param crs: The crs of this CubegenConfigCubeConfig. :type",
"spatial_res of this CubegenConfigCubeConfig. :type spatial_res: float \"\"\" if spatial_res is None: raise",
"self.openapi_types = { 'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date],",
"CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets the time_period",
"CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float] :param time_range: The time_range of this",
"of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets",
"\"\"\" return self._time_range @time_range.setter def time_range(self, time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig.",
"\"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig. :rtype:",
"variable_names is None: raise ValueError(\"Invalid value for `variable_names`, must not be `None`\") #",
"this CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str] :param crs: The crs of",
"this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names is None: raise ValueError(\"Invalid value",
"if time_range is None: raise ValueError(\"Invalid value for `time_range`, must not be `None`\")",
"time_range of this CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\"",
"def time_range(self, time_range): \"\"\"Sets the time_range of this CubegenConfigCubeConfig. :param time_range: The time_range",
"`None`\") # noqa: E501 self._variable_names = variable_names @property def crs(self): \"\"\"Gets the crs",
"F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This",
"time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as a model",
"The variable_names of this CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str] :param crs:",
"time_period): \"\"\"Sets the time_period of this CubegenConfigCubeConfig. :param time_period: The time_period of this",
":return: The crs of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter def",
"self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs', 'spatial_res': 'spatial_res', 'bbox': 'bbox', 'time_range': 'time_range',",
"spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of this",
"coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa:",
"this CubegenConfigCubeConfig. :param crs: The crs of this CubegenConfigCubeConfig. :type crs: str \"\"\"",
"ValueError(\"Invalid value for `variable_names`, must not be `None`\") # noqa: E501 self._variable_names =",
"class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class",
"self._spatial_res @spatial_res.setter def spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param spatial_res:",
"of this CubegenConfigCubeConfig. :param variable_names: The variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str]",
"# noqa: E501 :type variable_names: List[str] :param crs: The crs of this CubegenConfigCubeConfig.",
"This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the",
"self._bbox = bbox @property def time_range(self): \"\"\"Gets the time_range of this CubegenConfigCubeConfig. :return:",
"\"\"\" if time_period is None: raise ValueError(\"Invalid value for `time_period`, must not be",
"variable_names self._crs = crs self._spatial_res = spatial_res self._bbox = bbox self._time_range = time_range",
"cls) @property def variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return: The variable_names",
":param bbox: The bbox of this CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float]",
"CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period is None: raise ValueError(\"Invalid value for",
":param variable_names: The variable_names of this CubegenConfigCubeConfig. # noqa: E501 :type variable_names: List[str]",
"\"\"\" self.openapi_types = { 'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range':",
"is None: raise ValueError(\"Invalid value for `time_range`, must not be `None`\") # noqa:",
"spatial_res(self, spatial_res): \"\"\"Sets the spatial_res of this CubegenConfigCubeConfig. :param spatial_res: The spatial_res of",
"= time_range self._time_period = time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the",
"time_period of this CubegenConfigCubeConfig. :type time_period: str \"\"\" if time_period is None: raise",
"'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period': str }",
"bbox is None: raise ValueError(\"Invalid value for `bbox`, must not be `None`\") #",
"crs self._spatial_res = spatial_res self._bbox = bbox self._time_range = time_range self._time_period = time_period",
"is None: raise ValueError(\"Invalid value for `bbox`, must not be `None`\") # noqa:",
":return: The variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter def",
"time_period is None: raise ValueError(\"Invalid value for `time_period`, must not be `None`\") #",
"`variable_names`, must not be `None`\") # noqa: E501 self._variable_names = variable_names @property def",
"raise ValueError(\"Invalid value for `time_period`, must not be `None`\") # noqa: E501 self._time_period",
"List[float] :param time_range: The time_range of this CubegenConfigCubeConfig. # noqa: E501 :type time_range:",
"\"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig. :rtype:",
"\"\"\"CubegenConfigCubeConfig - a model defined in OpenAPI :param variable_names: The variable_names of this",
"as a model :param dikt: A dict. :type: dict :return: The CubegenConfig_cube_config of",
"str \"\"\" self.openapi_types = { 'variable_names': List[str], 'crs': str, 'spatial_res': float, 'bbox': List[float],",
"@bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox of this CubegenConfigCubeConfig. :param bbox: The",
":type time_period: str \"\"\" if time_period is None: raise ValueError(\"Invalid value for `time_period`,",
"defined in OpenAPI :param variable_names: The variable_names of this CubegenConfigCubeConfig. # noqa: E501",
":rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the variable_names of",
"util.deserialize_model(dikt, cls) @property def variable_names(self): \"\"\"Gets the variable_names of this CubegenConfigCubeConfig. :return: The",
"a model :param dikt: A dict. :type: dict :return: The CubegenConfig_cube_config of this",
":param bbox: The bbox of this CubegenConfigCubeConfig. :type bbox: List[float] \"\"\" if bbox",
"of this CubegenConfigCubeConfig. :return: The time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\" return",
"time_range of this CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date] :param time_period: The",
"variable_names: List[str] :param crs: The crs of this CubegenConfigCubeConfig. # noqa: E501 :type",
"spatial_res is None: raise ValueError(\"Invalid value for `spatial_res`, must not be `None`\") #",
"time_range of this CubegenConfigCubeConfig. :rtype: List[date] \"\"\" return self._time_range @time_range.setter def time_range(self, time_range):",
"CubegenConfigCubeConfig. :type crs: str \"\"\" if crs is None: raise ValueError(\"Invalid value for",
"CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter def bbox(self, bbox): \"\"\"Sets the bbox",
"# noqa: E501 :type crs: str :param spatial_res: The spatial_res of this CubegenConfigCubeConfig.",
"Generator (https://openapi-generator.tech). Do not edit the class manually. \"\"\" def __init__(self, variable_names=None, crs=None,",
"List[float], 'time_range': List[date], 'time_period': str } self.attribute_map = { 'variable_names': 'variable_names', 'crs': 'crs',",
"= spatial_res @property def bbox(self): \"\"\"Gets the bbox of this CubegenConfigCubeConfig. :return: The",
"'crs': str, 'spatial_res': float, 'bbox': List[float], 'time_range': List[date], 'time_period': str } self.attribute_map =",
"from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated by",
":param time_range: The time_range of this CubegenConfigCubeConfig. # noqa: E501 :type time_range: List[date]",
"@property def time_period(self): \"\"\"Gets the time_period of this CubegenConfigCubeConfig. :return: The time_period of",
"spatial_res: The spatial_res of this CubegenConfigCubeConfig. # noqa: E501 :type spatial_res: float :param",
"CubegenConfigCubeConfig. :return: The variable_names of this CubegenConfigCubeConfig. :rtype: List[str] \"\"\" return self._variable_names @variable_names.setter",
"be `None`\") # noqa: E501 self._bbox = bbox @property def time_range(self): \"\"\"Gets the",
"of this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\" return util.deserialize_model(dikt, cls) @property",
"self._time_range = time_range self._time_period = time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns",
"self._time_period = time_period @classmethod def from_dict(cls, dikt) -> 'CubegenConfigCubeConfig': \"\"\"Returns the dict as",
"CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names is None: raise ValueError(\"Invalid value for",
":type variable_names: List[str] \"\"\" if variable_names is None: raise ValueError(\"Invalid value for `variable_names`,",
"dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. # noqa: E501 :rtype: CubegenConfigCubeConfig \"\"\"",
"time_period: str \"\"\" if time_period is None: raise ValueError(\"Invalid value for `time_period`, must",
":param crs: The crs of this CubegenConfigCubeConfig. :type crs: str \"\"\" if crs",
"CubegenConfigCubeConfig. # noqa: E501 :type time_period: str \"\"\" self.openapi_types = { 'variable_names': List[str],",
"time_range: The time_range of this CubegenConfigCubeConfig. :type time_range: List[date] \"\"\" if time_range is",
"} self._variable_names = variable_names self._crs = crs self._spatial_res = spatial_res self._bbox = bbox",
"from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from",
"# noqa: E501 self._time_range = time_range @property def time_period(self): \"\"\"Gets the time_period of",
"CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not",
"E501 :type bbox: List[float] :param time_range: The time_range of this CubegenConfigCubeConfig. # noqa:",
":param dikt: A dict. :type: dict :return: The CubegenConfig_cube_config of this CubegenConfigCubeConfig. #",
"self._bbox = bbox self._time_range = time_range self._time_period = time_period @classmethod def from_dict(cls, dikt)",
"# noqa: F401 from typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_",
"by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. \"\"\" def __init__(self,",
"xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is auto generated by OpenAPI",
"# noqa: E501 :type spatial_res: float :param bbox: The bbox of this CubegenConfigCubeConfig.",
"spatial_res(self): \"\"\"Gets the spatial_res of this CubegenConfigCubeConfig. :return: The spatial_res of this CubegenConfigCubeConfig.",
":return: The time_period of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter def",
"CubegenConfigCubeConfig. :return: The bbox of this CubegenConfigCubeConfig. :rtype: List[float] \"\"\" return self._bbox @bbox.setter",
"the class manually. \"\"\" def __init__(self, variable_names=None, crs=None, spatial_res=None, bbox=None, time_range=None, time_period=None): #",
"CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._crs @crs.setter",
"F401 from typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model",
"the time_range of this CubegenConfigCubeConfig. :return: The time_range of this CubegenConfigCubeConfig. :rtype: List[date]",
"xcube_hub.models.base_model_ import Model from xcube_hub import util class CubegenConfigCubeConfig(Model): \"\"\"NOTE: This class is",
"`bbox`, must not be `None`\") # noqa: E501 self._bbox = bbox @property def",
"`time_range`, must not be `None`\") # noqa: E501 self._time_range = time_range @property def",
"this CubegenConfigCubeConfig. # noqa: E501 :type bbox: List[float] :param time_range: The time_range of",
"\"\"\"Gets the crs of this CubegenConfigCubeConfig. :return: The crs of this CubegenConfigCubeConfig. :rtype:",
"of this CubegenConfigCubeConfig. :rtype: str \"\"\" return self._time_period @time_period.setter def time_period(self, time_period): \"\"\"Sets",
":type spatial_res: float \"\"\" if spatial_res is None: raise ValueError(\"Invalid value for `spatial_res`,",
"variable_names: The variable_names of this CubegenConfigCubeConfig. :type variable_names: List[str] \"\"\" if variable_names is"
] |
[
"<filename>generalCredentials.py # General Chatbot Token telegramToken = \"\" # Announcement Channel ID announcementID",
"Chatbot Token telegramToken = \"\" # Announcement Channel ID announcementID = '' #",
"\"\" # Announcement Channel ID announcementID = '' # Dialogflow Project ID projectID",
"= \"\" # Announcement Channel ID announcementID = '' # Dialogflow Project ID",
"Token telegramToken = \"\" # Announcement Channel ID announcementID = '' # Dialogflow",
"telegramToken = \"\" # Announcement Channel ID announcementID = '' # Dialogflow Project",
"# General Chatbot Token telegramToken = \"\" # Announcement Channel ID announcementID =",
"# Announcement Channel ID announcementID = '' # Dialogflow Project ID projectID =",
"General Chatbot Token telegramToken = \"\" # Announcement Channel ID announcementID = ''",
"Announcement Channel ID announcementID = '' # Dialogflow Project ID projectID = \"newagent-XXXXXX\""
] |
[
"np x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función original xvals =",
"np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x, y) plt.plot(x, y, 'o') plt.plot(xvals, yinterp,",
"as plt import numpy as np x = np.linspace(0, 2*np.pi, 10) y =",
"xvals = np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x, y) plt.plot(x, y, 'o')",
"2*np.pi, 10) y = np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi, 50) yinterp",
"x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función original xvals = np.linspace(0,",
"np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x, y)",
"#Función original xvals = np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x, y) plt.plot(x,",
"= np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi,",
"y = np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals,",
"numpy as np x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función original",
"50) yinterp = np.interp(xvals, x, y) plt.plot(x, y, 'o') plt.plot(xvals, yinterp, '-x') plt.show()",
"import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2*np.pi, 10)",
"= np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x, y) plt.plot(x, y, 'o') plt.plot(xvals,",
"= np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x,",
"matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2*np.pi, 10) y",
"2*np.pi, 50) yinterp = np.interp(xvals, x, y) plt.plot(x, y, 'o') plt.plot(xvals, yinterp, '-x')",
"as np x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función original xvals",
"np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi, 50)",
"plt import numpy as np x = np.linspace(0, 2*np.pi, 10) y = np.sin(x)",
"10) y = np.sin(x) #Función original xvals = np.linspace(0, 2*np.pi, 50) yinterp =",
"import numpy as np x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) #Función",
"original xvals = np.linspace(0, 2*np.pi, 50) yinterp = np.interp(xvals, x, y) plt.plot(x, y,"
] |
[
"SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission',",
"url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end',",
"), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(),",
"import direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(),",
"{'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error',",
"url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$', direct_to_template, {'template': 'submission/success.html'}, name='success', ), )",
"), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$', direct_to_template, {'template': 'submission/success.html'}, name='success', ),",
"url from django.views.generic.simple import direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns =",
"direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission',",
"from django.views.generic.simple import direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('',",
"SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ),",
"import patterns, include, url from django.views.generic.simple import direct_to_template from .views import SubmissionView, SubmissionListView,",
"direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'},",
"), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template,",
"name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$', direct_to_template, {'template': 'submission/success.html'}, name='success',",
"name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$',",
"url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote',",
"'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ),",
"url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$', direct_to_template, {'template':",
"SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ),",
"django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from .views import SubmissionView,",
"from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ),",
"include, url from django.views.generic.simple import direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns",
"django.views.generic.simple import direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$',",
"from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from .views import",
"), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$', direct_to_template,",
"name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$',",
"SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$',",
"patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'},",
"= patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template':",
"urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template,",
".views import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$',",
"url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template':",
"name='end', ), url(r'^votar/$', SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$',",
"SubmissionListView.as_view(), name='vote', ), url(r'^votar/erro/$', direct_to_template, {'template': 'submission/error.html'}, name='error', ), url(r'^votar/success/$', direct_to_template, {'template': 'submission/success.html'},",
"import SubmissionView, SubmissionListView, SubmissionSuccess urlpatterns = patterns('', url(r'^$', SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(),",
"patterns, include, url from django.views.generic.simple import direct_to_template from .views import SubmissionView, SubmissionListView, SubmissionSuccess",
"SubmissionView.as_view(), name='submission', ), url(r'^success/$', SubmissionSuccess.as_view(), name='success_submission', ), url(r'^end/$', direct_to_template, {'template': 'submission/end.html'}, name='end', ),"
] |
[
"site key with areas site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance",
"site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance of Area.\"\"\" area =",
"with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class",
"attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method should raise an exception for",
"\"\"\"Get an instance of Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key = area.key",
"Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children`",
"area.key yield area def test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\" expected_key =",
"pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method",
"an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"): area.keys",
"from fixtures import get_title, get_url from craigslist_meta import Site selector = \"area\" #",
"def test_title(area, get_title): \"\"\"Test `title` attribute of area instance.\"\"\" area_title = area.title expected_title",
"import pytest from fixtures import get_title, get_url from craigslist_meta import Site selector =",
"import get_title, get_url from craigslist_meta import Site selector = \"area\" # use a",
"pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should",
"object has no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method should raise",
"area.all() def test_keys_raises(area): \"\"\"`keys` class method should raise an exception for Area.\"\"\" with",
"with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute",
"assert area_key == expected_key def test_title(area, get_title): \"\"\"Test `title` attribute of area instance.\"\"\"",
"no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method should raise an exception",
"area_key == expected_key def test_title(area, get_title): \"\"\"Test `title` attribute of area instance.\"\"\" area_title",
"area_url = area.url expected_url = get_url(selector, area_key) assert area_url == expected_url def test_all_raises(area):",
"get_title(selector, area_key) assert area_title == expected_title def test_url(area, get_url): \"\"\"Test `url` attribute of",
"assert area_title == expected_title def test_url(area, get_url): \"\"\"Test `url` attribute of area instance.\"\"\"",
"'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should raise an exception for Area.\"\"\" with",
"\"area\" # use a site key with areas site_key = \"sfbay\" @pytest.fixture def",
"an instance of Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key = area.key yield",
"Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key = area.key yield area def test_key(area):",
"area.url expected_url = get_url(selector, area_key) assert area_url == expected_url def test_all_raises(area): \"\"\"`all` class",
"method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no",
"area_key area_key = area.key yield area def test_key(area): \"\"\"Test `key` attribute of area",
"= \"area\" # use a site key with areas site_key = \"sfbay\" @pytest.fixture",
"area(): \"\"\"Get an instance of Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key =",
"expected_url def test_all_raises(area): \"\"\"`all` class method should raise an exception for Area.\"\"\" with",
"object has no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should raise an",
"\"\"\"Test `key` attribute of area instance.\"\"\" expected_key = area._key assert area_key == expected_key",
"\"\"\"Test `title` attribute of area instance.\"\"\" area_title = area.title expected_title = get_title(selector, area_key)",
"attribute should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no",
"area.keys def test_children_raises(area): \"\"\"`children` attribute should raise an exception for Area.\"\"\" with pytest.raises(AttributeError,",
"area instance.\"\"\" expected_key = area._key assert area_key == expected_key def test_title(area, get_title): \"\"\"Test",
"def test_url(area, get_url): \"\"\"Test `url` attribute of area instance.\"\"\" area_url = area.url expected_url",
"test_title(area, get_title): \"\"\"Test `title` attribute of area instance.\"\"\" area_title = area.title expected_title =",
"def test_all_raises(area): \"\"\"`all` class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError,",
"expected_key def test_title(area, get_title): \"\"\"Test `title` attribute of area instance.\"\"\" area_title = area.title",
"area = next(iter(Site(site_key))) global area_key area_key = area.key yield area def test_key(area): \"\"\"Test",
"raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"):",
"def test_keys_raises(area): \"\"\"`keys` class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError,",
"assert area_url == expected_url def test_all_raises(area): \"\"\"`all` class method should raise an exception",
"areas site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance of Area.\"\"\" area",
"= area.url expected_url = get_url(selector, area_key) assert area_url == expected_url def test_all_raises(area): \"\"\"`all`",
"'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method should raise an exception for Area.\"\"\"",
"instance.\"\"\" expected_key = area._key assert area_key == expected_key def test_title(area, get_title): \"\"\"Test `title`",
"area_key = area.key yield area def test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\"",
"instance of Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key = area.key yield area",
"for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"): area.keys def test_children_raises(area):",
"for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"): area.all() def test_keys_raises(area):",
"area_title == expected_title def test_url(area, get_url): \"\"\"Test `url` attribute of area instance.\"\"\" area_url",
"instance.\"\"\" area_title = area.title expected_title = get_title(selector, area_key) assert area_title == expected_title def",
"expected_url = get_url(selector, area_key) assert area_url == expected_url def test_all_raises(area): \"\"\"`all` class method",
"with areas site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance of Area.\"\"\"",
"has no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method should raise an",
"area instance.\"\"\" area_url = area.url expected_url = get_url(selector, area_key) assert area_url == expected_url",
"`key` attribute of area instance.\"\"\" expected_key = area._key assert area_key == expected_key def",
"def area(): \"\"\"Get an instance of Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key",
"= area.key yield area def test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\" expected_key",
"global area_key area_key = area.key yield area def test_key(area): \"\"\"Test `key` attribute of",
"Site selector = \"area\" # use a site key with areas site_key =",
"selector = \"area\" # use a site key with areas site_key = \"sfbay\"",
"= get_url(selector, area_key) assert area_url == expected_url def test_all_raises(area): \"\"\"`all` class method should",
"= area.title expected_title = get_title(selector, area_key) assert area_title == expected_title def test_url(area, get_url):",
"`title` attribute of area instance.\"\"\" area_title = area.title expected_title = get_title(selector, area_key) assert",
"\"\"\"`keys` class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object",
"import Site selector = \"area\" # use a site key with areas site_key",
"match=\"'Area' object has no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys` class method should",
"area._key assert area_key == expected_key def test_title(area, get_title): \"\"\"Test `title` attribute of area",
"area instance.\"\"\" area_title = area.title expected_title = get_title(selector, area_key) assert area_title == expected_title",
"test_keys_raises(area): \"\"\"`keys` class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area'",
"fixtures import get_title, get_url from craigslist_meta import Site selector = \"area\" # use",
"expected_title def test_url(area, get_url): \"\"\"Test `url` attribute of area instance.\"\"\" area_url = area.url",
"of area instance.\"\"\" area_url = area.url expected_url = get_url(selector, area_key) assert area_url ==",
"get_url): \"\"\"Test `url` attribute of area instance.\"\"\" area_url = area.url expected_url = get_url(selector,",
"has no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should raise an exception",
"of area instance.\"\"\" expected_key = area._key assert area_key == expected_key def test_title(area, get_title):",
"area.title expected_title = get_title(selector, area_key) assert area_title == expected_title def test_url(area, get_url): \"\"\"Test",
"test_children_raises(area): \"\"\"`children` attribute should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object",
"pytest from fixtures import get_title, get_url from craigslist_meta import Site selector = \"area\"",
"area_key) assert area_url == expected_url def test_all_raises(area): \"\"\"`all` class method should raise an",
"area_title = area.title expected_title = get_title(selector, area_key) assert area_title == expected_title def test_url(area,",
"def test_children_raises(area): \"\"\"`children` attribute should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area'",
"= \"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance of Area.\"\"\" area = next(iter(Site(site_key)))",
"instance.\"\"\" area_url = area.url expected_url = get_url(selector, area_key) assert area_url == expected_url def",
"= area._key assert area_key == expected_key def test_title(area, get_title): \"\"\"Test `title` attribute of",
"expected_title = get_title(selector, area_key) assert area_title == expected_title def test_url(area, get_url): \"\"\"Test `url`",
"exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"): area.all() def",
"attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should raise an exception for Area.\"\"\"",
"== expected_key def test_title(area, get_title): \"\"\"Test `title` attribute of area instance.\"\"\" area_title =",
"no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should raise an exception for",
"= get_title(selector, area_key) assert area_title == expected_title def test_url(area, get_url): \"\"\"Test `url` attribute",
"Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"): area.all() def test_keys_raises(area): \"\"\"`keys`",
"use a site key with areas site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get",
"\"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance of Area.\"\"\" area = next(iter(Site(site_key))) global",
"attribute of area instance.\"\"\" expected_key = area._key assert area_key == expected_key def test_title(area,",
"of Area.\"\"\" area = next(iter(Site(site_key))) global area_key area_key = area.key yield area def",
"area def test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\" expected_key = area._key assert",
"== expected_url def test_all_raises(area): \"\"\"`all` class method should raise an exception for Area.\"\"\"",
"get_url from craigslist_meta import Site selector = \"area\" # use a site key",
"area_url == expected_url def test_all_raises(area): \"\"\"`all` class method should raise an exception for",
"from craigslist_meta import Site selector = \"area\" # use a site key with",
"@pytest.fixture def area(): \"\"\"Get an instance of Area.\"\"\" area = next(iter(Site(site_key))) global area_key",
"\"\"\"`children` attribute should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has",
"\"\"\"Test `url` attribute of area instance.\"\"\" area_url = area.url expected_url = get_url(selector, area_key)",
"class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has",
"get_title): \"\"\"Test `title` attribute of area instance.\"\"\" area_title = area.title expected_title = get_title(selector,",
"def test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\" expected_key = area._key assert area_key",
"should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute",
"exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"): area.keys def",
"an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'children'\"): area.children",
"get_title, get_url from craigslist_meta import Site selector = \"area\" # use a site",
"\"\"\"`all` class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object",
"expected_key = area._key assert area_key == expected_key def test_title(area, get_title): \"\"\"Test `title` attribute",
"yield area def test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\" expected_key = area._key",
"of area instance.\"\"\" area_title = area.title expected_title = get_title(selector, area_key) assert area_title ==",
"raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'children'\"):",
"craigslist_meta import Site selector = \"area\" # use a site key with areas",
"attribute of area instance.\"\"\" area_url = area.url expected_url = get_url(selector, area_key) assert area_url",
"test_all_raises(area): \"\"\"`all` class method should raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area'",
"an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'all'\"): area.all()",
"match=\"'Area' object has no attribute 'keys'\"): area.keys def test_children_raises(area): \"\"\"`children` attribute should raise",
"a site key with areas site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get an",
"# use a site key with areas site_key = \"sfbay\" @pytest.fixture def area():",
"`url` attribute of area instance.\"\"\" area_url = area.url expected_url = get_url(selector, area_key) assert",
"attribute of area instance.\"\"\" area_title = area.title expected_title = get_title(selector, area_key) assert area_title",
"== expected_title def test_url(area, get_url): \"\"\"Test `url` attribute of area instance.\"\"\" area_url =",
"test_url(area, get_url): \"\"\"Test `url` attribute of area instance.\"\"\" area_url = area.url expected_url =",
"= next(iter(Site(site_key))) global area_key area_key = area.key yield area def test_key(area): \"\"\"Test `key`",
"area_key) assert area_title == expected_title def test_url(area, get_url): \"\"\"Test `url` attribute of area",
"next(iter(Site(site_key))) global area_key area_key = area.key yield area def test_key(area): \"\"\"Test `key` attribute",
"test_key(area): \"\"\"Test `key` attribute of area instance.\"\"\" expected_key = area._key assert area_key ==",
"key with areas site_key = \"sfbay\" @pytest.fixture def area(): \"\"\"Get an instance of",
"raise an exception for Area.\"\"\" with pytest.raises(AttributeError, match=\"'Area' object has no attribute 'keys'\"):",
"get_url(selector, area_key) assert area_url == expected_url def test_all_raises(area): \"\"\"`all` class method should raise"
] |
[
"b = 10 suma = a + b print(\"The addition is: \", suma)",
"5 b = 10 suma = a + b print(\"The addition is: \",",
"= 5 b = 10 suma = a + b print(\"The addition is:",
"<gh_stars>0 a = 5 b = 10 suma = a + b print(\"The",
"a = 5 b = 10 suma = a + b print(\"The addition"
] |
[
"division from __future__ import print_function import sys import os import argparse import numpy",
"all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist = [] for k,v in arg_params.iteritems():",
"for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in dellist: del arg_params[d]",
"sym = all_layers['relu1_output'] dellist = [] for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k)",
"mx.cpu(0) image_size = (112, 112) prefix = \"../models/resnet-50\" epoch = 0 sym, arg_params,",
"aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist = []",
"sym.get_internals() sym = all_layers['relu1_output'] dellist = [] for k,v in arg_params.iteritems(): if k.startswith('fc1'):",
"dellist.append(k) for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params) digraph",
"os import argparse import numpy as np import mxnet as mx ctx =",
"import print_function import sys import os import argparse import numpy as np import",
"= \"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers =",
"[] for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in dellist: del",
"print_function import sys import os import argparse import numpy as np import mxnet",
"del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params) digraph = mx.viz.plot_network(sym, shape={'data':(1,3,256,256)}, node_attrs={\"fixedsize\":\"false\"}) digraph.view()",
"__future__ import division from __future__ import print_function import sys import os import argparse",
"sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist",
"epoch = 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym",
"in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params) digraph = mx.viz.plot_network(sym, shape={'data':(1,3,256,256)},",
"import division from __future__ import print_function import sys import os import argparse import",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import sys",
"import numpy as np import mxnet as mx ctx = mx.cpu(0) image_size =",
"arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym,",
"= sym.get_internals() sym = all_layers['relu1_output'] dellist = [] for k,v in arg_params.iteritems(): if",
"= (112, 112) prefix = \"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params =",
"(112, 112) prefix = \"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix,",
"import sys import os import argparse import numpy as np import mxnet as",
"from __future__ import division from __future__ import print_function import sys import os import",
"epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist = [] for k,v in",
"all_layers['relu1_output'] dellist = [] for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d",
"112) prefix = \"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)",
"mx ctx = mx.cpu(0) image_size = (112, 112) prefix = \"../models/resnet-50\" epoch =",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist =",
"__future__ import print_function import sys import os import argparse import numpy as np",
"numpy as np import mxnet as mx ctx = mx.cpu(0) image_size = (112,",
"from __future__ import print_function import sys import os import argparse import numpy as",
"import mxnet as mx ctx = mx.cpu(0) image_size = (112, 112) prefix =",
"\"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals()",
"= mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist = [] for",
"np import mxnet as mx ctx = mx.cpu(0) image_size = (112, 112) prefix",
"prefix = \"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers",
"= [] for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in dellist:",
"dellist = [] for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in",
"= mx.cpu(0) image_size = (112, 112) prefix = \"../models/resnet-50\" epoch = 0 sym,",
"= 0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym =",
"= all_layers['relu1_output'] dellist = [] for k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for",
"mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output'] dellist = [] for k,v",
"dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params) digraph = mx.viz.plot_network(sym, shape={'data':(1,3,256,256)}, node_attrs={\"fixedsize\":\"false\"})",
"0 sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) all_layers = sym.get_internals() sym = all_layers['relu1_output']",
"k,v in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\",",
"import os import argparse import numpy as np import mxnet as mx ctx",
"as mx ctx = mx.cpu(0) image_size = (112, 112) prefix = \"../models/resnet-50\" epoch",
"ctx = mx.cpu(0) image_size = (112, 112) prefix = \"../models/resnet-50\" epoch = 0",
"as np import mxnet as mx ctx = mx.cpu(0) image_size = (112, 112)",
"image_size = (112, 112) prefix = \"../models/resnet-50\" epoch = 0 sym, arg_params, aux_params",
"in arg_params.iteritems(): if k.startswith('fc1'): dellist.append(k) for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0,",
"if k.startswith('fc1'): dellist.append(k) for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params,",
"k.startswith('fc1'): dellist.append(k) for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params)",
"import argparse import numpy as np import mxnet as mx ctx = mx.cpu(0)",
"d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params) digraph = mx.viz.plot_network(sym,",
"absolute_import from __future__ import division from __future__ import print_function import sys import os",
"mxnet as mx ctx = mx.cpu(0) image_size = (112, 112) prefix = \"../models/resnet-50\"",
"import absolute_import from __future__ import division from __future__ import print_function import sys import",
"for d in dellist: del arg_params[d] mx.model.save_checkpoint(prefix+\"s\", 0, sym, arg_params, aux_params) digraph =",
"argparse import numpy as np import mxnet as mx ctx = mx.cpu(0) image_size",
"sys import os import argparse import numpy as np import mxnet as mx"
] |
[
"= 4 top_k = 1 use_residual = False def run_test(rank, port): # 1.",
"- param : {module}\") return def test_expert_parallel_block(): world_size = 2 run_func = partial(run_test,",
"os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) #",
": {param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank} - param : {module}\") return",
"random from functools import partial import os import numpy as np import torch",
"Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create Model to expert-parallelize",
"#{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name, module in wrapper_ep.named_parameters(): if",
"wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank} - param_name",
"param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank} - param_name :",
"def test_expert_parallel_block(): world_size = 2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__",
"to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep = ExpertParallel( model_ep,",
"\"__main__\": # Set Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic = True",
"Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep = ExpertParallel(",
"torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1 use_residual = False def run_test(rank, port):",
"oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k",
"6. Print the result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" *",
": {module.size()}\" ) print(f\"Worker #{rank} - param : {module}\") return def test_expert_parallel_block(): world_size",
"if __name__ == \"__main__\": # Set Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0)",
"__name__ == \"__main__\": # Set Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic",
"Set Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark =",
"- param_name : {param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank} - param :",
"str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set",
"tokenizer.pad_token = tokenizer.eos_token # 4. Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) #",
"tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token",
"wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank} -",
"from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4",
"Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False test_expert_parallel_block()",
"num_experts = 4 top_k = 1 use_residual = False def run_test(rank, port): #",
"mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": # Set Random Seed for Reproducibility random.seed(0)",
"= tokenizer.eos_token # 4. Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5.",
"wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print",
"pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token =",
"import partial import os import numpy as np import torch import torch.multiprocessing as",
"# 4. Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model",
"if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank}",
"use_residual = False def run_test(rank, port): # 1. Configure for Parallelization os.environ[\"RANK\"] =",
"run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": # Set Random",
"data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token",
"): print( f\"Worker #{rank} - param_name : {param_name}, param_size : {module.size()}\" ) print(f\"Worker",
"AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\"))",
"os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"]",
"GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts =",
"wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank} - param_name : {param_name}, param_size :",
"print(\"=\" * 89) for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name )",
"import random from functools import partial import os import numpy as np import",
"of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name, module",
"5. Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, )",
"test_expert_parallel_block(): world_size = 2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ ==",
"os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1,",
"Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create",
"expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token #",
"Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6.",
"parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer",
"param_name ): print( f\"Worker #{rank} - param_name : {param_name}, param_size : {module.size()}\" )",
"torch.multiprocessing as mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel",
"= 1 use_residual = False def run_test(rank, port): # 1. Configure for Parallelization",
"str(port) # 2. Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2,",
") or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank} - param_name : {param_name},",
"4. Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep",
"param_name : {param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank} - param : {module}\")",
"ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1",
"use_residual=use_residual, ) # 6. Print the result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\")",
"import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode",
"2. Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) #",
"# 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create",
"str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port)",
"# 6. Print the result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\"",
"wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name, module in",
"param_size : {module.size()}\" ) print(f\"Worker #{rank} - param : {module}\") return def test_expert_parallel_block():",
"#{rank} - param : {module}\") return def test_expert_parallel_block(): world_size = 2 run_func =",
"ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1 use_residual = False def run_test(rank,",
"= AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create Model to expert-parallelize model_ep =",
": {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel(",
"print(wrapper_ep) print(\"=\" * 89) for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name",
"partial import os import numpy as np import torch import torch.multiprocessing as mp",
"wrapper_ep.model, param_name ): print( f\"Worker #{rank} - param_name : {param_name}, param_size : {module.size()}\"",
"print( f\"Worker #{rank} - param_name : {param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank}",
"<reponame>lipovsek/oslo<filename>tests/torch/nn/parallel/expert_parallel/wrapper_test/init_test/gpt2.py import random from functools import partial import os import numpy as np",
"f\"Worker #{rank} - param_name : {param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank} -",
"= ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer =",
"as mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from",
"np import torch import torch.multiprocessing as mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel",
"import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k =",
"Print the result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89)",
"89) for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel(",
"def run_test(rank, port): # 1. Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] =",
"import torch import torch.multiprocessing as mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from",
"GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False,",
"{wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model,",
"== \"__main__\": # Set Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic =",
"= str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2.",
"as np import torch import torch.multiprocessing as mp from transformers import AutoTokenizer, GPT2Config,",
"= False def run_test(rank, port): # 1. Configure for Parallelization os.environ[\"RANK\"] = str(rank)",
"= partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": # Set Random Seed",
"#{rank} - param_name : {param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank} - param",
"module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ):",
"{module}\") return def test_expert_parallel_block(): world_size = 2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size)",
"in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print(",
"Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False",
"param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name",
"{module.size()}\" ) print(f\"Worker #{rank} - param : {module}\") return def test_expert_parallel_block(): world_size =",
"print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name, module in wrapper_ep.named_parameters():",
"for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model,",
"tokenizer.eos_token # 4. Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap",
"2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": # Set",
"import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1 use_residual = False",
"# Set Random Seed for Reproducibility random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark",
"or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker #{rank} - param_name : {param_name}, param_size",
"numpy as np import torch import torch.multiprocessing as mp from transformers import AutoTokenizer,",
"torch import torch.multiprocessing as mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel",
"Create Model to expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep =",
"the result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for",
"= 2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": #",
"= ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the",
"3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create Model",
"functools import partial import os import numpy as np import torch import torch.multiprocessing",
"Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3.",
"tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create Model to expert-parallelize model_ep",
"Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"]",
"# 5. Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual,",
"oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1 use_residual =",
"world_size = 2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\":",
"4 top_k = 1 use_residual = False def run_test(rank, port): # 1. Configure",
") # 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4.",
"result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep) print(\"=\" * 89) for param_name,",
"wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or wrapper_ep.expert_parallel_mapping.is_behind_parallel( wrapper_ep.model, param_name ): print( f\"Worker",
"import os import numpy as np import torch import torch.multiprocessing as mp from",
"from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1 use_residual",
"model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the result of",
"False def run_test(rank, port): # 1. Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"]",
"\"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1,",
") print(f\"Worker #{rank} - param : {module}\") return def test_expert_parallel_block(): world_size = 2",
"GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts",
"param : {module}\") return def test_expert_parallel_block(): world_size = 2 run_func = partial(run_test, port=29500)",
"= \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel Context",
") # 6. Print the result of wrapping print(f\"Worker #{rank} : {wrapper_ep.device}\") print(wrapper_ep)",
"ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")",
"top_k = 1 use_residual = False def run_test(rank, port): # 1. Configure for",
"use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the result of wrapping print(f\"Worker #{rank} :",
": {module}\") return def test_expert_parallel_block(): world_size = 2 run_func = partial(run_test, port=29500) mp.spawn(run_func,",
"partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": # Set Random Seed for",
"\"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel Context parallel_context",
"from functools import partial import os import numpy as np import torch import",
"parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the result of wrapping",
"import torch.multiprocessing as mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import",
"ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000) num_experts = 4 top_k = 1 use_residual = False def",
"= str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] =",
"# 2. Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, )",
"num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the result of wrapping print(f\"Worker",
"nprocs=world_size) if __name__ == \"__main__\": # Set Random Seed for Reproducibility random.seed(0) np.random.seed(0)",
"import numpy as np import torch import torch.multiprocessing as mp from transformers import",
"run_test(rank, port): # 1. Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank)",
"port): # 1. Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"]",
"os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel",
"from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import",
"= \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel Context parallel_context = ParallelContext.from_torch(",
"AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext, ParallelMode torch.set_printoptions(threshold=10_000)",
"ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the result",
"Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1, use_kernel_optim=False, use_residual=use_residual, ) #",
"return def test_expert_parallel_block(): world_size = 2 run_func = partial(run_test, port=29500) mp.spawn(run_func, nprocs=world_size) if",
"Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] = \"localhost\"",
"= GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts, top_k=1,",
"# 1. Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] =",
"expert-parallelize model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context,",
"{param_name}, param_size : {module.size()}\" ) print(f\"Worker #{rank} - param : {module}\") return def",
"for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\" os.environ[\"MASTER_ADDR\"] =",
"print(f\"Worker #{rank} - param : {module}\") return def test_expert_parallel_block(): world_size = 2 run_func",
"1. Configure for Parallelization os.environ[\"RANK\"] = str(rank) os.environ[\"LOCAL_RANK\"] = str(rank) os.environ[\"WORLD_SIZE\"] = \"2\"",
"Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1, expert_parallel_size=2, ) # 3. Create Tokenizer",
"top_k=1, use_kernel_optim=False, use_residual=use_residual, ) # 6. Print the result of wrapping print(f\"Worker #{rank}",
"* 89) for param_name, module in wrapper_ep.named_parameters(): if wrapper_ep.expert_parallel_mapping.is_front_parallel( wrapper_ep.model, param_name ) or",
"Create Tokenizer tokenizer = AutoTokenizer.from_pretrained(\"gpt2\") tokenizer.pad_token = tokenizer.eos_token # 4. Create Model to",
"model_ep = GPT2LMHeadModel(GPT2Config.from_pretrained(\"gpt2\")) # 5. Wrap Model wrapper_ep = ExpertParallel( model_ep, parallel_context, num_experts=num_experts,",
"port=29500) mp.spawn(run_func, nprocs=world_size) if __name__ == \"__main__\": # Set Random Seed for Reproducibility",
"mp from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed",
"os import numpy as np import torch import torch.multiprocessing as mp from transformers",
"1 use_residual = False def run_test(rank, port): # 1. Configure for Parallelization os.environ[\"RANK\"]",
"os.environ[\"MASTER_ADDR\"] = \"localhost\" os.environ[\"MASTER_PORT\"] = str(port) # 2. Set Parallel Context parallel_context =",
"transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel from oslo.torch.nn.parallel.expert_parallel.expert_parallel import ExpertParallel from oslo.torch.distributed import ParallelContext,",
"= str(port) # 2. Set Parallel Context parallel_context = ParallelContext.from_torch( data_parallel_size=1, pipeline_parallel_size=1, tensor_parallel_size=1,"
] |
[
"ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3 = ioc.TSingleton3",
"__init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self,",
"pass class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__()",
"ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if",
"'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container():",
"TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3:",
"ts: TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class",
"self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self,",
"class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod def",
"cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False)",
"test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1',",
"ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs)",
"return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc",
"'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True)",
"TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts =",
"def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts = ts",
"**kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts:",
"class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts",
"get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3':",
"@staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name",
"ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1,",
"cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3",
"ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1",
"class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class",
"IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2',",
"cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3 = ioc.TSingleton3 assert isinstance(ts3, TSingleton3dot1) ioc.print_stats()",
"ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2,",
"def __init__(self, ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name,",
"return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False)",
"TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts =",
"__init__(self): pass class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2):",
"singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3 =",
"if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True)",
"return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2',",
"def __init__(self): pass class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts:",
"TSingleton1: def __init__(self): pass class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self,",
"flying_ioc import IocManager, IocFactory class TSingleton1: def __init__(self): pass class TSingleton2: def __init__(self):",
"cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False)",
"class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def",
"= IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False)",
"= ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs):",
"def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory)",
"pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3):",
"TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3):",
"= ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container':",
"__init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts = ts class",
"ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container': return",
"from flying_ioc import IocManager, IocFactory class TSingleton1: def __init__(self): pass class TSingleton2: def",
"class TSingleton1: def __init__(self): pass class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1): def",
"class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1",
"import IocManager, IocFactory class TSingleton1: def __init__(self): pass class TSingleton2: def __init__(self): pass",
"== 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1,",
"singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert",
"def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def",
"def get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name ==",
"frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2",
"self.ts = ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function ==",
"TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self,",
"class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts",
"ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3,",
"MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if",
"__init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts = ts class",
"singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3 = ioc.TSingleton3 assert isinstance(ts3,",
"**kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory):",
"frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3",
"IocFactory class TSingleton1: def __init__(self): pass class TSingleton2: def __init__(self): pass class TSingleton3(TSingleton1):",
"ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3 = ioc.TSingleton3 assert isinstance(ts3, TSingleton3dot1)",
"def __init__(self): pass class TSingleton3(TSingleton1): def __init__(self, ts: TSingleton2): super().__init__() self.ts = ts",
"ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3',",
"ioc.set_class(name='TSingleton1', cls=TSingleton1, singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2,",
"TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager,",
"== 'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def",
"IocManager, IocFactory class TSingleton1: def __init__(self): pass class TSingleton2: def __init__(self): pass class",
"super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def",
"__init__(self, ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info):",
"def __init__(self, ts: TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs):",
"super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod",
"name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc = IocManager(stats=True) ioc.set_class(name='TSingleton1',",
"name, frame_info): if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return",
"super().__init__(**kwargs) class TSingleton3dot1(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs) class TSingleton3dot3: def __init__(self, ts: TSingleton2):",
"ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1",
"singleton=True) ioc.set_class(name='TSingleton2', cls=TSingleton2, singleton=False) ioc.set_factory(name='TSingleton3', cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3',",
"if frame_info.function == 'test_factory_container': return ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return",
"__init__(self, ts: TSingleton2): super().__init__() self.ts = ts class TSingleton3dot2(TSingleton3): def __init__(self, **kwargs): super().__init__(**kwargs)",
"cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is ioc.TSingleton1 ts3 = ioc.TSingleton3 assert",
"TSingleton2): self.ts = ts class MyIocFactory(IocFactory): @staticmethod def get_instance(ioc_manager, name, frame_info): if frame_info.function",
"ioc_manager.TSingleton3dot1 if name == 'TSingleton3': return ioc_manager.TSingleton3dot2 return ioc_manager.TSingleton3dot3 def test_factory_container(): ioc =",
"cls=MyIocFactory) ioc.set_class(name='TSingleton3dot1', cls=TSingleton3dot1, singleton=False) ioc.set_class(name='TSingleton3dot2', cls=TSingleton3dot2, singleton=False) ioc.set_class(name='TSingleton3dot3', cls=TSingleton3dot3, singleton=False) assert ioc.TSingleton1 is"
] |
[
"} ] def find_smaller_edges(array): tmp = [] for val in array[1:]: if val",
"code. Sample: 10 ----------- 8 15 ----- ------- 5 12 94 --- _____",
"15, 2, 12, 11, 94, 81] }, 'output': True } ] def find_smaller_edges(array):",
"== 0: return True if arrayOne[0] != arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne)",
"takes in two arrays of integers and determines whether these arrays represent the",
"----- ------- 5 12 94 --- _____ _____ 2 11 81 \"\"\" testcases",
"arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2",
"val < array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp = [] for val",
"tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return False if len(arrayOne) ==",
"function that takes in two arrays of integers and determines whether these arrays",
"------- 5 12 94 --- _____ _____ 2 11 81 \"\"\" testcases =",
"in array[1:]: if val < array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp =",
"[10, 8, 5, 15, 2, 12, 11, 94, 81] }, 'output': True }",
"_____ 2 11 81 \"\"\" testcases = [ { 'input': { 'arrayOne': [10,",
">= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return",
"Same BSTs Write a function that takes in two arrays of integers and",
"two arrays of integers and determines whether these arrays represent the same BST.",
"BSTs Write a function that takes in two arrays of integers and determines",
"return tmp def find_bigger_edges(array): tmp = [] for val in array[1:]: if val",
"in array[1:]: if val >= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if",
"any BSTs in your code. Sample: 10 ----------- 8 15 ----- ------- 5",
"of integers and determines whether these arrays represent the same BST. Note that",
"] def find_smaller_edges(array): tmp = [] for val in array[1:]: if val <",
"for val in array[1:]: if val >= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne,",
"if val >= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) !=",
"not allowed to construct any BSTs in your code. Sample: 10 ----------- 8",
"and determines whether these arrays represent the same BST. Note that you're not",
"that you're not allowed to construct any BSTs in your code. Sample: 10",
"_____ _____ 2 11 81 \"\"\" testcases = [ { 'input': { 'arrayOne':",
"----------- 8 15 ----- ------- 5 12 94 --- _____ _____ 2 11",
"11 81 \"\"\" testcases = [ { 'input': { 'arrayOne': [10, 15, 8,",
"def find_smaller_edges(array): tmp = [] for val in array[1:]: if val < array[0]:",
"15, 8, 12, 94, 81, 5, 2, 11], 'arrayTwo': [10, 8, 5, 15,",
"81 \"\"\" testcases = [ { 'input': { 'arrayOne': [10, 15, 8, 12,",
"94, 81, 5, 2, 11], 'arrayTwo': [10, 8, 5, 15, 2, 12, 11,",
"sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return False if len(arrayOne) == len(arrayTwo) ==",
"5, 15, 2, 12, 11, 94, 81] }, 'output': True } ] def",
"the same BST. Note that you're not allowed to construct any BSTs in",
"Sample: 10 ----------- 8 15 ----- ------- 5 12 94 --- _____ _____",
"to construct any BSTs in your code. Sample: 10 ----------- 8 15 -----",
"= [ { 'input': { 'arrayOne': [10, 15, 8, 12, 94, 81, 5,",
"Write a function that takes in two arrays of integers and determines whether",
"= find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo) return sameBsts(left1,",
"12, 11, 94, 81] }, 'output': True } ] def find_smaller_edges(array): tmp =",
"== len(arrayTwo) == 0: return True if arrayOne[0] != arrayTwo[0]: return False left1",
"val in array[1:]: if val < array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp",
"BSTs in your code. Sample: 10 ----------- 8 15 ----- ------- 5 12",
"that takes in two arrays of integers and determines whether these arrays represent",
"\"\"\" Same BSTs Write a function that takes in two arrays of integers",
"tmp = [] for val in array[1:]: if val >= array[0]: tmp.append(val) return",
"{ 'input': { 'arrayOne': [10, 15, 8, 12, 94, 81, 5, 2, 11],",
"if val < array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp = [] for",
"in two arrays of integers and determines whether these arrays represent the same",
"left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo) return sameBsts(left1, left2) and",
"you're not allowed to construct any BSTs in your code. Sample: 10 -----------",
"10 ----------- 8 15 ----- ------- 5 12 94 --- _____ _____ 2",
"2, 12, 11, 94, 81] }, 'output': True } ] def find_smaller_edges(array): tmp",
"BST. Note that you're not allowed to construct any BSTs in your code.",
"[10, 15, 8, 12, 94, 81, 5, 2, 11], 'arrayTwo': [10, 8, 5,",
"tmp.append(val) return tmp def find_bigger_edges(array): tmp = [] for val in array[1:]: if",
"!= arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne)",
"your code. Sample: 10 ----------- 8 15 ----- ------- 5 12 94 ---",
"'arrayTwo': [10, 8, 5, 15, 2, 12, 11, 94, 81] }, 'output': True",
"8, 12, 94, 81, 5, 2, 11], 'arrayTwo': [10, 8, 5, 15, 2,",
"= [] for val in array[1:]: if val >= array[0]: tmp.append(val) return tmp",
"tmp = [] for val in array[1:]: if val < array[0]: tmp.append(val) return",
"'input': { 'arrayOne': [10, 15, 8, 12, 94, 81, 5, 2, 11], 'arrayTwo':",
"whether these arrays represent the same BST. Note that you're not allowed to",
"< array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp = [] for val in",
"len(arrayTwo): return False if len(arrayOne) == len(arrayTwo) == 0: return True if arrayOne[0]",
"--- _____ _____ 2 11 81 \"\"\" testcases = [ { 'input': {",
"array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp = [] for val in array[1:]:",
"len(arrayTwo) == 0: return True if arrayOne[0] != arrayTwo[0]: return False left1 =",
"True if arrayOne[0] != arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo)",
"find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo) return sameBsts(left1, left2) and sameBsts(right1, right2)",
"11], 'arrayTwo': [10, 8, 5, 15, 2, 12, 11, 94, 81] }, 'output':",
"if len(arrayOne) == len(arrayTwo) == 0: return True if arrayOne[0] != arrayTwo[0]: return",
"2 11 81 \"\"\" testcases = [ { 'input': { 'arrayOne': [10, 15,",
"return False if len(arrayOne) == len(arrayTwo) == 0: return True if arrayOne[0] !=",
"12, 94, 81, 5, 2, 11], 'arrayTwo': [10, 8, 5, 15, 2, 12,",
"Note that you're not allowed to construct any BSTs in your code. Sample:",
"False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo)",
"5, 2, 11], 'arrayTwo': [10, 8, 5, 15, 2, 12, 11, 94, 81]",
"= [] for val in array[1:]: if val < array[0]: tmp.append(val) return tmp",
"'arrayOne': [10, 15, 8, 12, 94, 81, 5, 2, 11], 'arrayTwo': [10, 8,",
"8, 5, 15, 2, 12, 11, 94, 81] }, 'output': True } ]",
"15 ----- ------- 5 12 94 --- _____ _____ 2 11 81 \"\"\"",
"val >= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo):",
"[ { 'input': { 'arrayOne': [10, 15, 8, 12, 94, 81, 5, 2,",
"same BST. Note that you're not allowed to construct any BSTs in your",
"False if len(arrayOne) == len(arrayTwo) == 0: return True if arrayOne[0] != arrayTwo[0]:",
"True } ] def find_smaller_edges(array): tmp = [] for val in array[1:]: if",
"!= len(arrayTwo): return False if len(arrayOne) == len(arrayTwo) == 0: return True if",
"8 15 ----- ------- 5 12 94 --- _____ _____ 2 11 81",
"allowed to construct any BSTs in your code. Sample: 10 ----------- 8 15",
"'output': True } ] def find_smaller_edges(array): tmp = [] for val in array[1:]:",
"tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return False if",
"testcases = [ { 'input': { 'arrayOne': [10, 15, 8, 12, 94, 81,",
"94 --- _____ _____ 2 11 81 \"\"\" testcases = [ { 'input':",
"{ 'arrayOne': [10, 15, 8, 12, 94, 81, 5, 2, 11], 'arrayTwo': [10,",
"array[1:]: if val < array[0]: tmp.append(val) return tmp def find_bigger_edges(array): tmp = []",
"these arrays represent the same BST. Note that you're not allowed to construct",
"5 12 94 --- _____ _____ 2 11 81 \"\"\" testcases = [",
"[] for val in array[1:]: if val >= array[0]: tmp.append(val) return tmp def",
"find_smaller_edges(array): tmp = [] for val in array[1:]: if val < array[0]: tmp.append(val)",
"determines whether these arrays represent the same BST. Note that you're not allowed",
"def find_bigger_edges(array): tmp = [] for val in array[1:]: if val >= array[0]:",
"represent the same BST. Note that you're not allowed to construct any BSTs",
"94, 81] }, 'output': True } ] def find_smaller_edges(array): tmp = [] for",
"0: return True if arrayOne[0] != arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2",
"11, 94, 81] }, 'output': True } ] def find_smaller_edges(array): tmp = []",
"arrays of integers and determines whether these arrays represent the same BST. Note",
"return False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 =",
"return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return False if len(arrayOne)",
"arrayTwo): if len(arrayOne) != len(arrayTwo): return False if len(arrayOne) == len(arrayTwo) == 0:",
"return True if arrayOne[0] != arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2 =",
"integers and determines whether these arrays represent the same BST. Note that you're",
"tmp def find_bigger_edges(array): tmp = [] for val in array[1:]: if val >=",
"}, 'output': True } ] def find_smaller_edges(array): tmp = [] for val in",
"\"\"\" testcases = [ { 'input': { 'arrayOne': [10, 15, 8, 12, 94,",
"arrayOne[0] != arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 =",
"in your code. Sample: 10 ----------- 8 15 ----- ------- 5 12 94",
"len(arrayOne) != len(arrayTwo): return False if len(arrayOne) == len(arrayTwo) == 0: return True",
"2, 11], 'arrayTwo': [10, 8, 5, 15, 2, 12, 11, 94, 81] },",
"arrays represent the same BST. Note that you're not allowed to construct any",
"81] }, 'output': True } ] def find_smaller_edges(array): tmp = [] for val",
"if arrayOne[0] != arrayTwo[0]: return False left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1",
"12 94 --- _____ _____ 2 11 81 \"\"\" testcases = [ {",
"find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo) return sameBsts(left1, left2)",
"for val in array[1:]: if val < array[0]: tmp.append(val) return tmp def find_bigger_edges(array):",
"construct any BSTs in your code. Sample: 10 ----------- 8 15 ----- -------",
"find_bigger_edges(array): tmp = [] for val in array[1:]: if val >= array[0]: tmp.append(val)",
"array[1:]: if val >= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne)",
"[] for val in array[1:]: if val < array[0]: tmp.append(val) return tmp def",
"val in array[1:]: if val >= array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo):",
"def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return False if len(arrayOne) == len(arrayTwo)",
"left1 = find_smaller_edges(arrayOne) left2 = find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo) return",
"a function that takes in two arrays of integers and determines whether these",
"if len(arrayOne) != len(arrayTwo): return False if len(arrayOne) == len(arrayTwo) == 0: return",
"array[0]: tmp.append(val) return tmp def sameBsts(arrayOne, arrayTwo): if len(arrayOne) != len(arrayTwo): return False",
"81, 5, 2, 11], 'arrayTwo': [10, 8, 5, 15, 2, 12, 11, 94,",
"= find_smaller_edges(arrayTwo) right1 = find_bigger_edges(arrayOne) right2 = find_bigger_edges(arrayTwo) return sameBsts(left1, left2) and sameBsts(right1,",
"len(arrayOne) == len(arrayTwo) == 0: return True if arrayOne[0] != arrayTwo[0]: return False"
] |
[
"user ratings. It gets user.user_rating2 and movie objects. Usage: .. code-block:: python {{",
"<filename>movies/templatetags/custom_filters.py from django import template from django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star')",
"user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating return rating except ObjectDoesNotExist: return 0",
"import template from django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie):",
"ratings. It gets user.user_rating2 and movie objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie",
"objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating",
"django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag",
"template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag which allows queryset filtering to",
"and movie objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating",
"\"\"\" Template tag which allows queryset filtering to get user ratings. It gets",
"allows queryset filtering to get user ratings. It gets user.user_rating2 and movie objects.",
"movie objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating =",
"python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating return rating except ObjectDoesNotExist:",
"filtering to get user ratings. It gets user.user_rating2 and movie objects. Usage: ..",
"It gets user.user_rating2 and movie objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }}",
"ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag which allows",
"@register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag which allows queryset filtering to get",
"to get user ratings. It gets user.user_rating2 and movie objects. Usage: .. code-block::",
"gets user.user_rating2 and movie objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\"",
"{{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating return rating except ObjectDoesNotExist: return",
"get user ratings. It gets user.user_rating2 and movie objects. Usage: .. code-block:: python",
"Template tag which allows queryset filtering to get user ratings. It gets user.user_rating2",
"from django import template from django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def",
"tag which allows queryset filtering to get user ratings. It gets user.user_rating2 and",
"queryset filtering to get user ratings. It gets user.user_rating2 and movie objects. Usage:",
"movie): \"\"\" Template tag which allows queryset filtering to get user ratings. It",
"user.user_rating2 and movie objects. Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try:",
"= template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag which allows queryset filtering",
"template from django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\"",
"Usage: .. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating return",
".. code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating return rating",
"import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag which",
"code-block:: python {{ user.user_rating2.all|user_star:movie }} \"\"\" try: rating = user_rating.get(movie=movie).user_rating return rating except",
"django import template from django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating,",
"register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template tag which allows queryset",
"def user_star(user_rating, movie): \"\"\" Template tag which allows queryset filtering to get user",
"which allows queryset filtering to get user ratings. It gets user.user_rating2 and movie",
"from django.core.exceptions import ObjectDoesNotExist register = template.Library() @register.filter(name='user_star') def user_star(user_rating, movie): \"\"\" Template",
"user_star(user_rating, movie): \"\"\" Template tag which allows queryset filtering to get user ratings."
] |
[] |
[
"'' content = '' nonce = 0 hash = '' def __init__(self, timestamp,",
"'' nonce = 0 hash = '' def __init__(self, timestamp, prev_hash, content, nonce,",
"'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce = 0 prev_hash =",
"% i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num):",
"self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self):",
"00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce =",
"for block in self.blocks: print('BLOCK #%d =======================' % i); i += 1 print(block.prev_hash)",
"= 0 hash = '' def __init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp",
"< self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1))",
"nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content,",
"self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1)) def",
"Genesis block: def __init__(self): nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis',",
"self.nonce = nonce self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE",
"__init__(self): nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def",
"if block_num > 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d",
"self.prev_hash = prev_hash self.content = content self.nonce = nonce self.hash = hash def",
"def add_block(self, content = ''): nonce = 0 prev_hash = self.blocks[-1].hash hash =",
"prev_hash = '' content = '' nonce = 0 hash = '' def",
"content, nonce, hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i =",
"# Faster, 32 bytes #md5 = md5('content').hexdigest() class Block: timestamp = '' prev_hash",
"= '' prev_hash = '' content = '' nonce = 0 hash =",
"in self.blocks: print('BLOCK #%d =======================' % i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content)",
"self.blocks: print('BLOCK #%d =======================' % i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash)",
"nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce = 0 prev_hash = self.blocks[-1].hash",
"block_num > 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is",
"time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain() print('Elapsed time: %.2fs' % (t2-t1)) b.check_chain()",
"self.prefix and nonce < self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce",
"= 0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] !=",
"#sha256 = sha256('content').hexdigest() # Faster, 32 bytes #md5 = md5('content').hexdigest() class Block: timestamp",
"self.timestamp = timestamp self.prev_hash = prev_hash self.content = content self.nonce = nonce self.hash",
"t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain() print('Elapsed time: %.2fs' %",
"time from hashlib import md5 from datetime import datetime ## Hashing functions: #",
"0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid' %",
"block number') def check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain()",
"md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid' % block_num) else: print('Block #%d is",
"self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 #",
"serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 # To prevent infinite mining",
"0 hash = '' def __init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp =",
"def check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 =",
"nonce < self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE:",
"def __init__(self): nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest()))",
"infinite mining prefix = '00000' # Mining difficulty blocks = [] # Genesis",
"< self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(),",
"print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for block in",
"#%d is invalid' % block_num) else: print('Invalid block number') def check_chain(self): for i",
"Mining: while hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE: nonce += 1 hash",
"while hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE: nonce += 1 hash =",
"hashlib import md5 from datetime import datetime ## Hashing functions: # Slower, 64",
"hash = '' def __init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp = timestamp",
"print('Invalid block number') def check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i) b =",
"add_block(self, content = ''): nonce = 0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest()",
"md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce = 0 prev_hash = self.blocks[-1].hash hash",
"For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce",
"nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable to mine block",
"0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix",
"timestamp = '' prev_hash = '' content = '' nonce = 0 hash",
"timestamp self.prev_hash = prev_hash self.content = content self.nonce = nonce self.hash = hash",
"#%d is valid' % block_num) else: print('Block #%d is invalid' % block_num) else:",
"= 1 for block in self.blocks: print('BLOCK #%d =======================' % i); i +=",
"import datetime ## Hashing functions: # Slower, 64 bytes #sha256 = sha256('content').hexdigest() #",
"Faster, 32 bytes #md5 = md5('content').hexdigest() class Block: timestamp = '' prev_hash =",
"b = Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain() print('Elapsed",
"[] # Genesis block: def __init__(self): nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(),",
"= content self.nonce = nonce self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class",
"self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 # To prevent infinite mining prefix =",
"1 for block in self.blocks: print('BLOCK #%d =======================' % i); i += 1",
"from hashlib import md5 from datetime import datetime ## Hashing functions: # Slower,",
"check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 = time()",
"32 bytes #md5 = md5('content').hexdigest() class Block: timestamp = '' prev_hash = ''",
"def print_chain(self): i = 1 for block in self.blocks: print('BLOCK #%d =======================' %",
"i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num",
"## Hashing functions: # Slower, 64 bytes #sha256 = sha256('content').hexdigest() # Faster, 32",
"== block.hash: print('Block #%d is valid' % block_num) else: print('Block #%d is invalid'",
"def check_block(self, block_num): if block_num > 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() ==",
"content = ''): nonce = 0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() #",
"block_num) else: print('Invalid block number') def check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i)",
"block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for block in self.blocks: print('BLOCK #%d",
"in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2",
"= Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain() print('Elapsed time:",
"= md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable",
"'' prev_hash = '' content = '' nonce = 0 hash = ''",
"invalid' % block_num) else: print('Invalid block number') def check_chain(self): for i in range(1,",
"= time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain() print('Elapsed time: %.2fs' % (t2-t1))",
"hash): self.timestamp = timestamp self.prev_hash = prev_hash self.content = content self.nonce = nonce",
"bytes #md5 = md5('content').hexdigest() class Block: timestamp = '' prev_hash = '' content",
"blocks = [] # Genesis block: def __init__(self): nonce = 622722 # For",
"% block_num) else: print('Block #%d is invalid' % block_num) else: print('Invalid block number')",
"prevent infinite mining prefix = '00000' # Mining difficulty blocks = [] #",
"sha256('content').hexdigest() # Faster, 32 bytes #md5 = md5('content').hexdigest() class Block: timestamp = ''",
"mining prefix = '00000' # Mining difficulty blocks = [] # Genesis block:",
"datetime ## Hashing functions: # Slower, 64 bytes #sha256 = sha256('content').hexdigest() # Faster,",
"print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num > 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest()",
"from time import time from hashlib import md5 from datetime import datetime ##",
"i = 1 for block in self.blocks: print('BLOCK #%d =======================' % i); i",
"# Mining difficulty blocks = [] # Genesis block: def __init__(self): nonce =",
"def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 # To prevent infinite",
"class Blockchain: MAX_NONCE = 999999 # To prevent infinite mining prefix = '00000'",
"timestamp, prev_hash, content, nonce, hash): self.timestamp = timestamp self.prev_hash = prev_hash self.content =",
"To prevent infinite mining prefix = '00000' # Mining difficulty blocks = []",
"datetime import datetime ## Hashing functions: # Slower, 64 bytes #sha256 = sha256('content').hexdigest()",
"import time from hashlib import md5 from datetime import datetime ## Hashing functions:",
"to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for block in self.blocks:",
"block_num) else: print('Block #%d is invalid' % block_num) else: print('Invalid block number') def",
"MAX_NONCE = 999999 # To prevent infinite mining prefix = '00000' # Mining",
"block: def __init__(self): nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce,",
"# Slower, 64 bytes #sha256 = sha256('content').hexdigest() # Faster, 32 bytes #md5 =",
"1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num > 0:",
"nonce self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999",
"return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 # To prevent infinite mining prefix",
"'' def __init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp = timestamp self.prev_hash =",
"if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable to mine",
"from datetime import datetime ## Hashing functions: # Slower, 64 bytes #sha256 =",
"valid' % block_num) else: print('Block #%d is invalid' % block_num) else: print('Invalid block",
"= sha256('content').hexdigest() # Faster, 32 bytes #md5 = md5('content').hexdigest() class Block: timestamp =",
"print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num > 0: block",
"self.check_block(i) b = Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain()",
"self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix and nonce <",
"print('Block #%d is valid' % block_num) else: print('Block #%d is invalid' % block_num)",
"% block_num) else: print('Invalid block number') def check_chain(self): for i in range(1, len(self.blocks)+1):",
"difficulty blocks = [] # Genesis block: def __init__(self): nonce = 622722 #",
"= self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid' % block_num) else:",
"md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE: nonce +=",
"md5 from datetime import datetime ## Hashing functions: # Slower, 64 bytes #sha256",
"64 bytes #sha256 = sha256('content').hexdigest() # Faster, 32 bytes #md5 = md5('content').hexdigest() class",
"content = '' nonce = 0 hash = '' def __init__(self, timestamp, prev_hash,",
"self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash,",
"print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num > 0: block = self.blocks[block_num-1]",
"print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num > 0: block = self.blocks[block_num-1] if",
"+= 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce,",
"content self.nonce = nonce self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain:",
"= md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE: nonce",
"md5('content').hexdigest() class Block: timestamp = '' prev_hash = '' content = '' nonce",
"block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid' % block_num)",
"= timestamp self.prev_hash = prev_hash self.content = content self.nonce = nonce self.hash =",
"else: print('Block #%d is invalid' % block_num) else: print('Invalid block number') def check_chain(self):",
"+= 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num >",
"=======================' % i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self,",
"nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self,",
"prev_hash self.content = content self.nonce = nonce self.hash = hash def serialize(self): return",
"i in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle')",
"Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 = time() b.print_chain() print('Elapsed time: %.2fs'",
"# For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''):",
"block.hash: print('Block #%d is valid' % block_num) else: print('Block #%d is invalid' %",
"Blockchain: MAX_NONCE = 999999 # To prevent infinite mining prefix = '00000' #",
"= ''): nonce = 0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining:",
"nonce = 0 hash = '' def __init__(self, timestamp, prev_hash, content, nonce, hash):",
"print('Block #%d is invalid' % block_num) else: print('Invalid block number') def check_chain(self): for",
"prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix and",
"i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if",
"nonce = 0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)]",
"#md5 = md5('content').hexdigest() class Block: timestamp = '' prev_hash = '' content =",
"and nonce < self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce <",
"= '' nonce = 0 hash = '' def __init__(self, timestamp, prev_hash, content,",
"# Genesis block: def __init__(self): nonce = 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32),",
"mine block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for block in self.blocks: print('BLOCK",
"# Mining: while hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE: nonce += 1",
"hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 # To prevent",
"number') def check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1",
"'00000' # Mining difficulty blocks = [] # Genesis block: def __init__(self): nonce",
"self.content = content self.nonce = nonce self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce)",
"check_block(self, block_num): if block_num > 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash:",
"= '00000' # Mining difficulty blocks = [] # Genesis block: def __init__(self):",
"= prev_hash self.content = content self.nonce = nonce self.hash = hash def serialize(self):",
"= 622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content",
"range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 =",
"block in self.blocks: print('BLOCK #%d =======================' % i); i += 1 print(block.prev_hash) print(block.timestamp)",
"Mining difficulty blocks = [] # Genesis block: def __init__(self): nonce = 622722",
"def __init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp = timestamp self.prev_hash = prev_hash",
"content, nonce, hash): self.timestamp = timestamp self.prev_hash = prev_hash self.content = content self.nonce",
"''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce = 0 prev_hash",
"nonce, hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1",
"else: print('Invalid block number') def check_chain(self): for i in range(1, len(self.blocks)+1): self.check_block(i) b",
"bytes #sha256 = sha256('content').hexdigest() # Faster, 32 bytes #md5 = md5('content').hexdigest() class Block:",
"1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash))",
"> 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid'",
"print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def check_block(self, block_num): if block_num > 0: block =",
"prefix = '00000' # Mining difficulty blocks = [] # Genesis block: def",
"Slower, 64 bytes #sha256 = sha256('content').hexdigest() # Faster, 32 bytes #md5 = md5('content').hexdigest()",
"hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest()",
"''): nonce = 0 prev_hash = self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while",
"= self.blocks[-1].hash hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix and nonce",
"= '' def __init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp = timestamp self.prev_hash",
"hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() # Mining: while hash[0:len(self.prefix)] != self.prefix and nonce < self.MAX_NONCE:",
"md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else: print('Unable to",
"nonce, hash): self.timestamp = timestamp self.prev_hash = prev_hash self.content = content self.nonce =",
"!= self.prefix and nonce < self.MAX_NONCE: nonce += 1 hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if",
"= '' content = '' nonce = 0 hash = '' def __init__(self,",
"#%d =======================' % i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV') def",
"Hashing functions: # Slower, 64 bytes #sha256 = sha256('content').hexdigest() # Faster, 32 bytes",
"import md5 from datetime import datetime ## Hashing functions: # Slower, 64 bytes",
"len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 = time() b.add_block('Johnny') b.add_block('Noelle') t2 = time()",
"#'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for block in self.blocks: print('BLOCK #%d ======================='",
"print_chain(self): i = 1 for block in self.blocks: print('BLOCK #%d =======================' % i);",
"functions: # Slower, 64 bytes #sha256 = sha256('content').hexdigest() # Faster, 32 bytes #md5",
"time import time from hashlib import md5 from datetime import datetime ## Hashing",
"print('BLOCK #%d =======================' % i); i += 1 print(block.prev_hash) print(block.timestamp) print(block.content) print(block.hash) print('================================\\n\\t\\t|\\n\\t\\tV')",
"999999 # To prevent infinite mining prefix = '00000' # Mining difficulty blocks",
"prev_hash, content, nonce, hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i",
"= 999999 # To prevent infinite mining prefix = '00000' # Mining difficulty",
"prev_hash, content, nonce, hash): self.timestamp = timestamp self.prev_hash = prev_hash self.content = content",
"self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid' % block_num) else: print('Block",
"class Block: timestamp = '' prev_hash = '' content = '' nonce =",
"= nonce self.hash = hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE =",
"622722 # For 00000 self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content =",
"hash)) else: print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for",
"is invalid' % block_num) else: print('Invalid block number') def check_chain(self): for i in",
"= md5('content').hexdigest() class Block: timestamp = '' prev_hash = '' content = ''",
"__init__(self, timestamp, prev_hash, content, nonce, hash): self.timestamp = timestamp self.prev_hash = prev_hash self.content",
"if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block #%d is valid' % block_num) else: print('Block #%d",
"block_num): if block_num > 0: block = self.blocks[block_num-1] if md5((block.serialize()).encode('utf-8')).hexdigest() == block.hash: print('Block",
"Block: timestamp = '' prev_hash = '' content = '' nonce = 0",
"= [] # Genesis block: def __init__(self): nonce = 622722 # For 00000",
"for i in range(1, len(self.blocks)+1): self.check_block(i) b = Blockchain() t1 = time() b.add_block('Johnny')",
"# To prevent infinite mining prefix = '00000' # Mining difficulty blocks =",
"self.blocks.append(Block(datetime.now(), ''.zfill(32), 'Genesis', nonce, md5((''.zfill(32)+'Genesis'+str(nonce)).encode('utf-8')).hexdigest())) def add_block(self, content = ''): nonce = 0",
"hash = md5((prev_hash+content+str(nonce)).encode('utf-8')).hexdigest() if nonce < self.MAX_NONCE: self.blocks.append(Block(datetime.now(), prev_hash, content, nonce, hash)) else:",
"is valid' % block_num) else: print('Block #%d is invalid' % block_num) else: print('Invalid",
"= hash def serialize(self): return self.prev_hash+self.content+str(self.nonce) class Blockchain: MAX_NONCE = 999999 # To",
"else: print('Unable to mine block #'+str(len(self.blocks)+1)) def print_chain(self): i = 1 for block"
] |
[
"0: energy += won_battles else: print(f'Not enough energy! Game ends with {won_battles} won",
"distance = input() won_battles = 0 while distance != 'End of battle': distance",
"if won_battles % 3 == 0: energy += won_battles else: print(f'Not enough energy!",
"distance = input() if distance == 'End of battle': print(f'Won battles: {won_battles}. Energy",
"of battle': distance = int(distance) if energy >= distance: energy -= distance won_battles",
"input() if distance == 'End of battle': print(f'Won battles: {won_battles}. Energy left: {energy}')",
"if energy >= distance: energy -= distance won_battles += 1 if won_battles %",
"int(input()) distance = input() won_battles = 0 while distance != 'End of battle':",
"+= won_battles else: print(f'Not enough energy! Game ends with {won_battles} won battles and",
"0 while distance != 'End of battle': distance = int(distance) if energy >=",
"distance won_battles += 1 if won_battles % 3 == 0: energy += won_battles",
"1 if won_battles % 3 == 0: energy += won_battles else: print(f'Not enough",
"distance = int(distance) if energy >= distance: energy -= distance won_battles += 1",
"distance: energy -= distance won_battles += 1 if won_battles % 3 == 0:",
"= 0 while distance != 'End of battle': distance = int(distance) if energy",
"{energy} energy') break distance = input() if distance == 'End of battle': print(f'Won",
"and {energy} energy') break distance = input() if distance == 'End of battle':",
">= distance: energy -= distance won_battles += 1 if won_battles % 3 ==",
"energy >= distance: energy -= distance won_battles += 1 if won_battles % 3",
"enough energy! Game ends with {won_battles} won battles and {energy} energy') break distance",
"-= distance won_battles += 1 if won_battles % 3 == 0: energy +=",
"!= 'End of battle': distance = int(distance) if energy >= distance: energy -=",
"won_battles % 3 == 0: energy += won_battles else: print(f'Not enough energy! Game",
"3 == 0: energy += won_battles else: print(f'Not enough energy! Game ends with",
"energy += won_battles else: print(f'Not enough energy! Game ends with {won_battles} won battles",
"Game ends with {won_battles} won battles and {energy} energy') break distance = input()",
"battles and {energy} energy') break distance = input() if distance == 'End of",
"print(f'Not enough energy! Game ends with {won_battles} won battles and {energy} energy') break",
"won_battles = 0 while distance != 'End of battle': distance = int(distance) if",
"= int(input()) distance = input() won_battles = 0 while distance != 'End of",
"'End of battle': distance = int(distance) if energy >= distance: energy -= distance",
"% 3 == 0: energy += won_battles else: print(f'Not enough energy! Game ends",
"break distance = input() if distance == 'End of battle': print(f'Won battles: {won_battles}.",
"won battles and {energy} energy') break distance = input() if distance == 'End",
"= input() won_battles = 0 while distance != 'End of battle': distance =",
"battle': distance = int(distance) if energy >= distance: energy -= distance won_battles +=",
"else: print(f'Not enough energy! Game ends with {won_battles} won battles and {energy} energy')",
"input() won_battles = 0 while distance != 'End of battle': distance = int(distance)",
"int(distance) if energy >= distance: energy -= distance won_battles += 1 if won_battles",
"won_battles else: print(f'Not enough energy! Game ends with {won_battles} won battles and {energy}",
"= int(distance) if energy >= distance: energy -= distance won_battles += 1 if",
"= input() if distance == 'End of battle': print(f'Won battles: {won_battles}. Energy left:",
"+= 1 if won_battles % 3 == 0: energy += won_battles else: print(f'Not",
"won_battles += 1 if won_battles % 3 == 0: energy += won_battles else:",
"energy -= distance won_battles += 1 if won_battles % 3 == 0: energy",
"with {won_battles} won battles and {energy} energy') break distance = input() if distance",
"energy! Game ends with {won_battles} won battles and {energy} energy') break distance =",
"energy') break distance = input() if distance == 'End of battle': print(f'Won battles:",
"== 0: energy += won_battles else: print(f'Not enough energy! Game ends with {won_battles}",
"{won_battles} won battles and {energy} energy') break distance = input() if distance ==",
"ends with {won_battles} won battles and {energy} energy') break distance = input() if",
"energy = int(input()) distance = input() won_battles = 0 while distance != 'End",
"distance != 'End of battle': distance = int(distance) if energy >= distance: energy",
"while distance != 'End of battle': distance = int(distance) if energy >= distance:"
] |
[
"from .definition import Definition, Profile, ConfigurationTemplate from .connectivity_info import ConnectivityInfo from .instance import",
"Definition, Profile, ConfigurationTemplate from .connectivity_info import ConnectivityInfo from .instance import InstantiationParameter, InstantiationRequest, Instance",
".definition import Definition, Profile, ConfigurationTemplate from .connectivity_info import ConnectivityInfo from .instance import InstantiationParameter,",
"package.\"\"\" from .definition import Definition, Profile, ConfigurationTemplate from .connectivity_info import ConnectivityInfo from .instance",
"\"\"\"K8s package.\"\"\" from .definition import Definition, Profile, ConfigurationTemplate from .connectivity_info import ConnectivityInfo from",
"import Definition, Profile, ConfigurationTemplate from .connectivity_info import ConnectivityInfo from .instance import InstantiationParameter, InstantiationRequest,"
] |
[
"__init__(self, config): super().__init__(config) pass def _my_method(self): pass factory = MockFactory({'key': 'value'}) method =",
"= MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method == factory._my_method assert factory.config ==",
"import Factory def test_factory_extract() -> None: class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass",
"def test_factory_extract() -> None: class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def _my_method(self):",
"config): super().__init__(config) pass def _my_method(self): pass factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method')",
"pass def _my_method(self): pass factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method",
"super().__init__(config) pass def _my_method(self): pass factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert",
"injectark import Factory def test_factory_extract() -> None: class MockFactory(Factory): def __init__(self, config): super().__init__(config)",
"'value'}) method = factory.extract('_my_method') assert method == factory._my_method assert factory.config == {'key': 'value'}",
"None: class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def _my_method(self): pass factory =",
"def __init__(self, config): super().__init__(config) pass def _my_method(self): pass factory = MockFactory({'key': 'value'}) method",
"-> None: class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def _my_method(self): pass factory",
"MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def _my_method(self): pass factory = MockFactory({'key': 'value'})",
"Factory def test_factory_extract() -> None: class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def",
"factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method == factory._my_method assert factory.config",
"def _my_method(self): pass factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method ==",
"MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method == factory._my_method assert factory.config == {'key':",
"pass factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method == factory._my_method assert",
"_my_method(self): pass factory = MockFactory({'key': 'value'}) method = factory.extract('_my_method') assert method == factory._my_method",
"test_factory_extract() -> None: class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def _my_method(self): pass",
"class MockFactory(Factory): def __init__(self, config): super().__init__(config) pass def _my_method(self): pass factory = MockFactory({'key':",
"from injectark import Factory def test_factory_extract() -> None: class MockFactory(Factory): def __init__(self, config):"
] |
[
"1))), axis=2)) def __del__(self): self.sess.close() def fit(self, A, b): return self.sess.run(self.distance_tf, feed_dict={self.A_tf: A,",
"self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf =",
"self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None,",
"axis=2)) def __del__(self): self.sess.close() def fit(self, A, b): return self.sess.run(self.distance_tf, feed_dict={self.A_tf: A, self.b_tf:",
"tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))),",
"self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf,",
"tensorflow as tf class Distance: def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph)",
"class Distance: def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf",
"tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def fit(self, A, b): return self.sess.run(self.distance_tf, feed_dict={self.A_tf:",
"= tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf,",
"division from __future__ import print_function import tensorflow as tf class Distance: def __init__(self):",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow",
"self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32)",
"dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def fit(self, A,",
"__future__ import division from __future__ import print_function import tensorflow as tf class Distance:",
"tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf =",
"print_function import tensorflow as tf class Distance: def __init__(self): self.graph = tf.Graph() self.sess",
"512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def fit(self,",
"= tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512],",
"self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self):",
"with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf",
"tf class Distance: def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default():",
"import absolute_import from __future__ import division from __future__ import print_function import tensorflow as",
"__future__ import print_function import tensorflow as tf class Distance: def __init__(self): self.graph =",
"from __future__ import division from __future__ import print_function import tensorflow as tf class",
"as tf class Distance: def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with",
"dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"= tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf",
"import print_function import tensorflow as tf class Distance: def __init__(self): self.graph = tf.Graph()",
"= tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def fit(self, A, b): return",
"import tensorflow as tf class Distance: def __init__(self): self.graph = tf.Graph() self.sess =",
"512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2))",
"tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def",
"import division from __future__ import print_function import tensorflow as tf class Distance: def",
"def __del__(self): self.sess.close() def fit(self, A, b): return self.sess.run(self.distance_tf, feed_dict={self.A_tf: A, self.b_tf: b})",
"Distance: def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf =",
"def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None,",
"__init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512],",
"tf.Session(graph=self.graph) with self.graph.as_default(): self.b_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32) self.A_tf = tf.placeholder(shape=[None, 512], dtype=tf.float32)",
"from __future__ import print_function import tensorflow as tf class Distance: def __init__(self): self.graph",
"self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def fit(self, A, b):",
"absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf",
"tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close() def fit(self, A, b): return self.sess.run(self.distance_tf,",
"= tf.placeholder(shape=[None, 512], dtype=tf.float32) self.distance_tf = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(self.A_tf, tf.expand_dims(self.b_tf, 1))), axis=2)) def __del__(self): self.sess.close()"
] |
[
"# unittest.main() def run_main_test(): suite = unittest.TestSuite() suite.addTest(TestPostVectorMethods(\"test\")) runner = unittest.TextTestRunner() runner.run(suite) run_main_test()",
"wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def test(self): print",
"import os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ =",
"if __name__ == '__main__': # unittest.main() def run_main_test(): suite = unittest.TestSuite() suite.addTest(TestPostVectorMethods(\"test\")) runner",
"import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text'))",
"= WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ == '__main__':",
"self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ == '__main__': # unittest.main() def run_main_test(): suite",
"# text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self):",
"print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ == '__main__': # unittest.main() def run_main_test():",
"sys import time import os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')",
"'..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import",
"import sys import time import os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__),",
"sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api",
"'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def",
"TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass",
"os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase):",
"pass if __name__ == '__main__': # unittest.main() def run_main_test(): suite = unittest.TestSuite() suite.addTest(TestPostVectorMethods(\"test\"))",
"setUp(self): self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__",
"text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api",
"import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES')",
"TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC",
"tearDown(self): pass if __name__ == '__main__': # unittest.main() def run_main_test(): suite = unittest.TestSuite()",
"import time import os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') #",
"from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def test(self):",
"test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ == '__main__': # unittest.main() def",
"os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC()",
"os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR,",
"def setUp(self): self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if",
"def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ == '__main__': # unittest.main()",
"'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def",
"unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from",
"self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ ==",
"time import os import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') # text_",
"__name__ == '__main__': # unittest.main() def run_main_test(): suite = unittest.TestSuite() suite.addTest(TestPostVectorMethods(\"test\")) runner =",
"def tearDown(self): pass if __name__ == '__main__': # unittest.main() def run_main_test(): suite =",
"= os.path.join(os.path.dirname(__file__), 'data') # text_ = os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class",
"WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def",
"class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api = WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self):",
"WEDC() def test(self): print self.api.config('WEDC_CATEGORIES') def tearDown(self): pass if __name__ == '__main__': #",
"= os.path.expanduser(os.path.join(TEST_DATA_DIR, 'text')) from wedc.application.api import WEDC class TestPostVectorMethods(unittest.TestCase): def setUp(self): self.api =",
"== '__main__': # unittest.main() def run_main_test(): suite = unittest.TestSuite() suite.addTest(TestPostVectorMethods(\"test\")) runner = unittest.TextTestRunner()",
"'__main__': # unittest.main() def run_main_test(): suite = unittest.TestSuite() suite.addTest(TestPostVectorMethods(\"test\")) runner = unittest.TextTestRunner() runner.run(suite)"
] |
[
"\"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600 Games\", } # Populate entries",
"DQN2013 paper. 7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries import entries",
"\"\"\" Contingency scores from DQN2013 paper. 7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\"",
"# Specify ALGORITHM algo = { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\":",
"\"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600 Games\", } # Populate entries entries",
".entries import entries # Specify ALGORITHM algo = { # ALGORITHM \"algo-title\": \"Contingency\",",
"from DQN2013 paper. 7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries import",
"unique entries \"\"\" from .entries import entries # Specify ALGORITHM algo = {",
"7 unique entries \"\"\" from .entries import entries # Specify ALGORITHM algo =",
"Specify ALGORITHM algo = { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating",
"Contingency Awareness Using Atari 2600 Games\", } # Populate entries entries = [{**entry,",
"algo = { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness",
"# Populate entries entries = [{**entry, **algo} for entry in entries] assert len(entries)",
"scores from DQN2013 paper. 7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries",
"7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries import entries # Specify",
"ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600 Games\",",
"Populate entries entries = [{**entry, **algo} for entry in entries] assert len(entries) ==",
"= { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using",
"entries # Specify ALGORITHM algo = { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\",",
"Awareness Using Atari 2600 Games\", } # Populate entries entries = [{**entry, **algo}",
"2600 Games\", } # Populate entries entries = [{**entry, **algo} for entry in",
"<reponame>seungjaeryanlee/sotarl \"\"\" Contingency scores from DQN2013 paper. 7 entries ------------------------------------------------------------------------ 7 unique entries",
"ALGORITHM algo = { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency",
"entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries import entries # Specify ALGORITHM",
"paper. 7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries import entries #",
"{ # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari",
"Games\", } # Populate entries entries = [{**entry, **algo} for entry in entries]",
"# ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600",
"from .entries import entries # Specify ALGORITHM algo = { # ALGORITHM \"algo-title\":",
"Atari 2600 Games\", } # Populate entries entries = [{**entry, **algo} for entry",
"import entries # Specify ALGORITHM algo = { # ALGORITHM \"algo-title\": \"Contingency\", \"algo-nickname\":",
"------------------------------------------------------------------------ 7 unique entries \"\"\" from .entries import entries # Specify ALGORITHM algo",
"\"algo-title\": \"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600 Games\", }",
"} # Populate entries entries = [{**entry, **algo} for entry in entries] assert",
"\"Contingency\", \"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600 Games\", } #",
"Contingency scores from DQN2013 paper. 7 entries ------------------------------------------------------------------------ 7 unique entries \"\"\" from",
"entries entries = [{**entry, **algo} for entry in entries] assert len(entries) == 7",
"\"\"\" from .entries import entries # Specify ALGORITHM algo = { # ALGORITHM",
"entries \"\"\" from .entries import entries # Specify ALGORITHM algo = { #",
"Using Atari 2600 Games\", } # Populate entries entries = [{**entry, **algo} for",
"\"algo-nickname\": \"Contingency\", \"algo-source-title\": \"Investigating Contingency Awareness Using Atari 2600 Games\", } # Populate",
"\"Investigating Contingency Awareness Using Atari 2600 Games\", } # Populate entries entries ="
] |
[
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"== \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network' -or \" \\ \"-name",
"-name 'test.network' -or \" \\ \"-name 'test.netdev' -or -name 'test.link' -or -name 'test.swport'",
"/etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network' -or \" \\ \"-name 'test.netdev' -or",
"MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n",
"'test.netdev' -or -name 'test.link' -or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command =",
"assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network' -or",
"-name 'extra1.link' -or -name 'extra1.swport' -or \" \\ \"-name 'extra2.network' -or -name 'extra2.netdev'",
"this file except in compliance with the License. # You may obtain a",
"unittest.mock import MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command =",
"-or -name 'test1.swport' -or \" \\ \"-name 'test2.network' -or -name 'test2.netdev' -or -name",
"-delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert",
"'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport' \\\\)",
"NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\(",
"ANY KIND, either express or implied. # See the License for the specific",
"'extra1.swport' -or -name 'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or",
"NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\(",
"/etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network' -or \" \\ \"-name 'test1.netdev' -or",
"-or \" \\ \"-name 'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or \"",
"\" \\ \"-name 'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport' -or \" \\",
"-name 'test2.link' -or \" \\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command =",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"# limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import MagicMock",
"-not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\",",
"n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\\ \"-name 'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name",
"test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][",
"assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network' -or",
"OF ANY KIND, either express or implied. # See the License for the",
"NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings()",
"\" \\ \"-name 'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev' -or \" \\",
"\\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings()",
"-or \" \\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link' -or \"",
"#!/usr/bin/env python # Copyright (c) 2015 - 2017, Intel Corporation. # # Licensed",
"-name 'test.link' -or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n",
"'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\",",
"permissions and # limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock",
"-delete\" def test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"\"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\(",
"\"-name 'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command",
"-name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' -or -name 'extra1.network'",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or",
"'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport' -or \" \\ \"-name 'extra2.network' -or",
"0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network' -or \" \\",
"-or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command,",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"])",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network' -or",
"= NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not",
"required by applicable law or agreed to in writing, software # distributed under",
"2015 - 2017, Intel Corporation. # # Licensed under the Apache License, Version",
"'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link' -or \" \\ \"-name 'extra2.swport' \\\\)",
"-name 'extra1.swport' -or \" \\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link'",
"governing permissions and # limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from",
"applicable law or agreed to in writing, software # distributed under the License",
"= MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/",
"== \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network' -or \" \\ \"-name",
"or agreed to in writing, software # distributed under the License is distributed",
"\\ \"-name 'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network' -or \" \\ \"-name",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network' -or \"",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"= MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"\\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link' -or \" \\ \"-name",
"-or -name 'extra1.swport' -or -name 'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or -name",
"\"-name 'test.netdev' -or -name 'test.link' -or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\"",
"License. # You may obtain a copy of the License at # #",
"\\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"])",
"-or \" \\ \"-name 'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network' -or \"",
"test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0]",
"compliance with the License. # You may obtain a copy of the License",
"run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] ==",
"'extra1.link' -or -name 'extra1.swport' -or \" \\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or",
"\"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network'",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network'",
"-mindepth 1 -not \\\\( -name 'test.network' -or \" \\ \"-name 'test.netdev' -or -name",
"n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth",
"-not \\\\( -name 'test1.network' -or \" \\ \"-name 'test1.netdev' -or -name 'test1.link' -or",
"'test.link' -or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n =",
"-delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"])",
"-or -name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' \\\\) -delete\"",
"not use this file except in compliance with the License. # You may",
"== \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network' -or \" \\ \"-name",
"NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"-name 'test1.link' -or -name 'test1.swport' -or \" \\ \"-name 'test2.network' -or -name 'test2.netdev'",
"\\ \"-name 'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport' -or \" \\ \"-name",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"\" \\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link' -or \" \\",
"'test1.network' -or \" \\ \"-name 'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport' -or",
"# you may not use this file except in compliance with the License.",
"agreed to in writing, software # distributed under the License is distributed on",
"\" \\ \"-name 'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network' -or \" \\",
"'test2.link' -or \" \\ \"-name 'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev' -or",
"\"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock()",
"from unittest.mock import MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command",
"(the \"License\"); # you may not use this file except in compliance with",
"\" \\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command = MagicMock() n =",
"under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import MagicMock from testlib.linux.networkd",
"# Unless required by applicable law or agreed to in writing, software #",
"= NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth",
"-not \\\\( -name 'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or",
"by applicable law or agreed to in writing, software # distributed under the",
"\"-name 'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport' -or \" \\ \"-name 'test2.network'",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"[\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\(",
"= MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find",
"'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' -or -name 'extra1.network' -or",
"-or -name 'extra1.network' -or -name 'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or -name",
"file except in compliance with the License. # You may obtain a copy",
"= MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] ==",
"-not \\\\( -name 'test.network' -or \" \\ \"-name 'test.netdev' -or -name 'test.link' -or",
"-or \" \\ \"-name 'test.netdev' -or -name 'test.link' -or -name 'test.swport' \\\\) -delete\"",
"and # limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import",
"Corporation. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"License for the specific language governing permissions and # limitations under the License.",
"'test2.link' -or \" \\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command = MagicMock()",
"[\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name",
"-mindepth 1 -not \\\\( -name 'test1.network' -or \" \\ \"-name 'test1.netdev' -or -name",
"MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth",
"to in writing, software # distributed under the License is distributed on an",
"the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import MagicMock from testlib.linux.networkd import",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"-or -name 'test1.link' -or -name 'test1.swport' -or \" \\ \"-name 'test2.network' -or -name",
"'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command =",
"-name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' \\\\) -delete\" def",
"n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/",
"def test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert",
"import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test\"])",
"-or -name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock()",
"-or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command,",
"or implied. # See the License for the specific language governing permissions and",
"-or -name 'test.link' -or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock()",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command",
"-name 'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport'",
"in writing, software # distributed under the License is distributed on an \"AS",
"'extra1.network' -or -name 'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or -name 'extra1.swport' -or",
"run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] ==",
"specific language governing permissions and # limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests`",
"\\\\( -name 'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or -name",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"-or -name 'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or -name",
"= NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1",
"= MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find",
"\\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"])",
"'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' \\\\)",
"[]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\)",
"-name 'test2.link' -or \" \\ \"-name 'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev'",
"MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/",
"\\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\",",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings()",
"Unittests` \"\"\" from unittest.mock import MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object): def",
"you may not use this file except in compliance with the License. #",
"1 -not \\\\( -name 'test1.network' -or \" \\ \"-name 'test1.netdev' -or -name 'test1.link'",
"\\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command,",
"testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command,",
"\" \\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def",
"test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0]",
"-name 'extra1.network' -or -name 'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or -name 'extra1.swport'",
"'test1.link' -or -name 'test1.swport' -or \" \\ \"-name 'test2.network' -or -name 'test2.netdev' -or",
"-or -name 'test2.link' -or \" \\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command",
"use this file except in compliance with the License. # You may obtain",
"Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"-or \" \\ \"-name 'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport' -or \"",
"== \"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command =",
"limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import MagicMock from",
"n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth",
"'test.network' -or \" \\ \"-name 'test.netdev' -or -name 'test.link' -or -name 'test.swport' \\\\)",
"test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] ==",
"Copyright (c) 2015 - 2017, Intel Corporation. # # Licensed under the Apache",
"\\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport' -or \" \\ \"-name",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"'extra1.swport' -or \" \\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link' -or",
"-or \" \\ \"-name 'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev' -or \"",
"-or \" \\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\"",
"'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport' -or \" \\ \"-name 'test2.network' -or",
"-mindepth 1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n =",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find",
"MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/",
"def test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][",
"/etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"\\ \"-name 'extra2.netdev' -or -name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self):",
"1 -not \\\\( -name 'test.network' -or \" \\ \"-name 'test.netdev' -or -name 'test.link'",
"class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert",
"1 -not \\\\( -name 'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or -name 'extra1.link'",
"# # Unless required by applicable law or agreed to in writing, software",
"express or implied. # See the License for the specific language governing permissions",
"'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' -or",
"-name 'test1.network' -or \" \\ \"-name 'test1.netdev' -or -name 'test1.link' -or -name 'test1.swport'",
"\"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network' -or \" \\ \"-name 'extra1.netdev'",
"\\\\( -name 'test.network' -or \" \\ \"-name 'test.netdev' -or -name 'test.link' -or -name",
"either express or implied. # See the License for the specific language governing",
"NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not",
"- 2017, Intel Corporation. # # Licensed under the Apache License, Version 2.0",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"run_command = MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find",
"= NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not",
"\"\"\" from unittest.mock import MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self):",
"python # Copyright (c) 2015 - 2017, Intel Corporation. # # Licensed under",
"'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport' -or",
"the License. # You may obtain a copy of the License at #",
"NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1",
"test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] ==",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self):",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"\\ \"-name 'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev' -or \" \\ \"-name",
"-or -name 'extra1.link' -or -name 'extra1.swport' -or \" \\ \"-name 'extra2.network' -or -name",
"\"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name",
"n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1",
"-name 'test1.swport' -or \" \\ \"-name 'test2.network' -or -name 'test2.netdev' -or -name 'test2.link'",
"\"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network' -or \" \\ \"-name 'test.netdev'",
"run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network' -or \"",
"\"-name 'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport' -or \" \\ \"-name 'extra2.network'",
"-or \" \\ \"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command = MagicMock() n",
"2017, Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the",
"the specific language governing permissions and # limitations under the License. \"\"\"``test_networkd.py`` `NetworkD",
"License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import MagicMock from testlib.linux.networkd import NetworkD",
"with the License. # You may obtain a copy of the License at",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"-delete\" def test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][",
"def test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0]",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"\" \\ \"-name 'test.netdev' -or -name 'test.link' -or -name 'test.swport' \\\\) -delete\" def",
"run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0]",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"for the specific language governing permissions and # limitations under the License. \"\"\"``test_networkd.py``",
"import MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock()",
"0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test.network' -or \" \\",
"-name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock() n = NetworkD(run_command, [])",
"def test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][",
"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",
"\"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network' -or \" \\ \"-name 'test1.netdev'",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"-or -name 'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or -name 'extra1.swport' -or -name",
"\" \\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport' -or \" \\",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"-name 'extra1.netdev' -or \" \\ \"-name 'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network'",
"\"-name 'test2.swport' \\\\) -delete\" def test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command, [])",
"See the License for the specific language governing permissions and # limitations under",
"\" \\ \"-name 'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or \" \\",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"-name 'test2.swport' -or -name 'extra1.network' -or -name 'extra1.netdev' -or \" \\ \"-name 'extra1.link'",
"run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"def test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert run_command.call_args_list[0][0][ 0]",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"\"-name 'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport'",
"\\\\) -delete\" def test_empty_list(self): run_command = MagicMock() n = NetworkD(run_command, []) n.clear_settings() assert",
"[]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\(",
"language governing permissions and # limitations under the License. \"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\"",
"[\"test1\", \"test2\"]) n.clear_settings(exclude_ports=[\"extra1\", \"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not",
"-or \" \\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport' -or \"",
"from testlib.linux.networkd import NetworkD class TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n =",
"assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\" def",
"\\\\( -name 'test1.network' -or \" \\ \"-name 'test1.netdev' -or -name 'test1.link' -or -name",
"run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self):",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"-name 'extra1.swport' -or -name 'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or -name 'extra2.link'",
"-or -name 'extra2.netdev' -or -name 'extra2.link' -or \" \\ \"-name 'extra2.swport' \\\\) -delete\"",
"assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network' -or",
"-or -name 'extra1.swport' -or \" \\ \"-name 'extra2.network' -or -name 'extra2.netdev' -or -name",
"-or -name 'test2.netdev' -or -name 'test2.link' -or \" \\ \"-name 'test2.swport' -or -name",
"-name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test1\",",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"\"extra2\"]) assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network'",
"-mindepth 1 -not \\\\( -name 'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or -name",
"MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth",
"\"-name 'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network' -or \" \\ \"-name 'extra2.netdev'",
"= NetworkD(run_command, [\"test1\", \"test2\"]) n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1",
"run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network' -or \"",
"'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock() n =",
"\"-name 'extra2.network' -or -name 'extra2.netdev' -or -name 'extra2.link' -or \" \\ \"-name 'extra2.swport'",
"'extra1.link' -or -name 'extra1.swport' -or -name 'extra2.network' -or \" \\ \"-name 'extra2.netdev' -or",
"-name 'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or -name 'extra1.link' -or -name 'extra1.swport'",
"-name 'extra2.link' -or -name 'extra2.swport' \\\\) -delete\" def test_just_extra_excludes(self): run_command = MagicMock() n",
"'test1.swport' -or \" \\ \"-name 'test2.network' -or -name 'test2.netdev' -or -name 'test2.link' -or",
"-or -name 'test2.link' -or \" \\ \"-name 'test2.swport' -or -name 'extra1.network' -or -name",
"/etc/systemd/network/ -mindepth 1 -not \\\\( -name 'extra1.network' -or \" \\ \"-name 'extra1.netdev' -or",
"\"\"\"``test_networkd.py`` `NetworkD Unittests` \"\"\" from unittest.mock import MagicMock from testlib.linux.networkd import NetworkD class",
"# Copyright (c) 2015 - 2017, Intel Corporation. # # Licensed under the",
"TestNetworkD(object): def test_single_mgmt_port(self): run_command = MagicMock() n = NetworkD(run_command, [\"test\"]) n.clear_settings() assert run_command.call_args_list[0][0][",
"(c) 2015 - 2017, Intel Corporation. # # Licensed under the Apache License,",
"`NetworkD Unittests` \"\"\" from unittest.mock import MagicMock from testlib.linux.networkd import NetworkD class TestNetworkD(object):",
"n.clear_settings() assert run_command.call_args_list[0][0][ 0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network'",
"0] == \"find /etc/systemd/network/ -mindepth 1 -not \\\\( -name 'test1.network' -or \" \\",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"\\ \"-name 'test.netdev' -or -name 'test.link' -or -name 'test.swport' \\\\) -delete\" def test_multiple_mgmt_port(self):",
"1 -not \\\\( \\\\) -delete\" def test_extra_excludes_are_appended(self): run_command = MagicMock() n = NetworkD(run_command,"
] |
[
"= [] for user_or_group in [user, *groups]: # Filter out identical notifications that",
"notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification = await",
"# performed an access deny operation locally under \"RoleA\" with session name =",
"However, \"UserA\" is a member of \"GroupA\", which owns RoleA. We want #",
"if v.expiration > current_time ] # Show newest notifications first notifications_for_user = sorted(",
"want # to show the notification to members of \"GroupA\", as well as",
"force_refresh or ( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications",
"captured via user-specific attribution. IE: \"UserA\" # performed an access deny operation locally",
"locally under \"RoleA\" with session name = \"UserA\", so the generated # notification",
"v.expiration > current_time ] # Show newest notifications first notifications_for_user = sorted( notifications_for_user,",
"log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications = []",
"RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False):",
"True continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id:",
"existing_user_notification.predictable_id ): seen = True if not seen: notifications_for_user.append(notification) # Filter out \"expired\"",
"# notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception()",
"Skip this notification if it isn't hidden for the user continue seen =",
"async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function =",
"time from collections import defaultdict from typing import Dict import sentry_sdk import ujson",
"return self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse:",
"log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1: # Skip unsupported versions",
"redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys()",
"{ \"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time())",
"asgiref.sync import sync_to_async from consoleme.config import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3,",
"of \"GroupA\", which owns RoleA. We want # to show the notification to",
"we don't want \"UserA\" to see 2 # notifications. notifications = all_notifications.get(user_or_group) if",
"want \"UserA\" to see 2 # notifications. notifications = all_notifications.get(user_or_group) if not notifications:",
"# Show newest notifications first notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True",
"collections import defaultdict from typing import Dict import sentry_sdk import ujson as json",
"Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\": function} ddb",
"import time from collections import defaultdict from typing import Dict import sentry_sdk import",
"config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from",
"tied to the user. However, \"UserA\" is a member of \"GroupA\", which owns",
"seen = False for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if",
"self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={},",
"notification if it isn't hidden for the user continue seen = False for",
"> config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\",",
"notification is tied to the user. However, \"UserA\" is a member of \"GroupA\",",
"of as an array # to account for future changes to the model",
"Filter out identical notifications that were already captured via user-specific attribution. IE: \"UserA\"",
"async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time()) - self.last_update > config.get(",
"\"GroupA\", which owns RoleA. We want # to show the notification to members",
"seen = True if not seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user",
"notifications_for_user = [ v for v in notifications_for_user if v.expiration > current_time ]",
"def cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data =",
"from consoleme.lib.singleton import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update =",
"to members of \"GroupA\", as well as \"UserA\" but we don't want \"UserA\"",
"notification to members of \"GroupA\", as well as \"UserA\" but we don't want",
"import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler",
"2 # notifications. notifications = all_notifications.get(user_or_group) if not notifications: continue notifications = json.loads(notifications)",
"] # Show newest notifications first notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time,",
"store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] =",
"= int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user =",
"-> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\": function}",
"log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def",
"to the user. However, \"UserA\" is a member of \"GroupA\", which owns RoleA.",
"import sys import time from collections import defaultdict from typing import Dict import",
"isn't hidden for the user continue seen = False for existing_user_notification_raw in notifications_for_user:",
"notification.version != 1: # Skip unsupported versions of the notification model continue if",
"continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str):",
"existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id ): seen = True if not",
"an access deny operation locally under \"RoleA\" with session name = \"UserA\", so",
"i.event_time, reverse=True ) # Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in",
"0 notifications_for_user = [] for user_or_group in [user, *groups]: # Filter out identical",
"s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time()) return self.all_notifications async",
"notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user in notification.read_by_users or notification.read_by_all:",
"log_data = { \"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time",
"s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time()) return self.all_notifications async def",
"sentry_sdk.capture_exception() continue if notification.version != 1: # Skip unsupported versions of the notification",
"s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l)",
"out identical notifications that were already captured via user-specific attribution. IE: \"UserA\" #",
"as original_json import sys import time from collections import defaultdict from typing import",
"the notification model continue if user in notification.hidden_for_users: # Skip this notification if",
"existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired = True",
") if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]: function =",
"( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from",
"cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), )",
"SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log",
"changed_notifications) if notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await",
"that may invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e:",
"{\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications",
"e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1: # Skip unsupported",
"notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return,",
"unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)(",
"notification model continue if user in notification.hidden_for_users: # Skip this notification if it",
"if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue unread_count += 1",
"UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from",
"= ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in",
"notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue",
"from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder",
"await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() ->",
"ujson as json from asgiref.sync import sync_to_async from consoleme.config import config from consoleme.lib.cache",
"if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\"",
"force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\":",
"force_refresh ) unread_count = 0 notifications_for_user = [] for user_or_group in [user, *groups]:",
"json from asgiref.sync import sync_to_async from consoleme.config import config from consoleme.lib.cache import (",
"def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} )",
"notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v in notifications_by_user_group.items():",
"notifications: try: # We parse ConsoleMeUserNotification individually instead of as an array #",
"!= 1: # Skip unsupported versions of the notification model continue if user",
"len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification):",
"len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)( Item=ddb._data_to_dynamo_replace(notification.dict()) )",
"changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for",
"all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in all_notifications_l: notification =",
"import defaultdict from typing import Dict import sentry_sdk import ujson as json from",
"notifications_for_user if v.expiration > current_time ] # Show newest notifications first notifications_for_user =",
"= config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications = [] async",
"notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if",
"): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ),",
"in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict())",
"if force_refresh or ( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ):",
"if current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict())",
"may invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data,",
"to the model that may invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except",
"ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder)",
"model that may invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as",
"consoleme.config import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import",
"notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def",
"= 0 notifications_for_user = [] for user_or_group in [user, *groups]: # Filter out",
"user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue unread_count += 1 return",
"import sentry_sdk import ujson as json from asgiref.sync import sync_to_async from consoleme.config import",
"True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group:",
"in notifications_to_return: if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue unread_count",
"notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]: function",
"= sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True ) # Increment Unread Count notifications_to_return",
"UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async",
"via user-specific attribution. IE: \"UserA\" # performed an access deny operation locally under",
"function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications =",
"from typing import Dict import sentry_sdk import ujson as json from asgiref.sync import",
"max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\":",
"current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user",
"import json as original_json import sys import time from collections import defaultdict from",
"notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group",
"default={}, ) self.last_update = int(time.time()) return self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\",",
"is a member of \"GroupA\", which owns RoleA. We want # to show",
"notifications. notifications = all_notifications.get(user_or_group) if not notifications: continue notifications = json.loads(notifications) for notification_raw",
"True if not seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user = [",
"in notifications: try: # We parse ConsoleMeUserNotification individually instead of as an array",
"function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications =",
"consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import",
"\"UserA\" but we don't want \"UserA\" to see 2 # notifications. notifications =",
"parse ConsoleMeUserNotification individually instead of as an array # to account for future",
"user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications(",
"= [ v for v in notifications_for_user if v.expiration > current_time ] #",
"the model that may invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception",
"notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group,",
"if not seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user = [ v",
"f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, }",
"def retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\",",
"# Filter out identical notifications that were already captured via user-specific attribution. IE:",
"notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications)",
"== existing_user_notification.predictable_id ): seen = True if not seen: notifications_for_user.append(notification) # Filter out",
"if it isn't hidden for the user continue seen = False for existing_user_notification_raw",
"an array # to account for future changes to the model that may",
"= { \"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time =",
"Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user in",
"\"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time()) return self.all_notifications async def get_notifications_for_user(",
"\"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1: # Skip unsupported versions of",
"instead of as an array # to account for future changes to the",
"await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user = [] for user_or_group in",
"await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update",
"fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if",
"changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v,",
"continue notifications = json.loads(notifications) for notification_raw in notifications: try: # We parse ConsoleMeUserNotification",
"s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] =",
"well as \"UserA\" but we don't want \"UserA\" to see 2 # notifications.",
"False for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id",
"( notification.predictable_id == existing_user_notification.predictable_id ): seen = True if not seen: notifications_for_user.append(notification) #",
"as well as \"UserA\" but we don't want \"UserA\" to see 2 #",
"[] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time()) - self.last_update >",
"-> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\": user, \"max_notifications\":",
"self.last_update = int(time.time()) return self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False,",
"defaultdict from typing import Dict import sentry_sdk import ujson as json from asgiref.sync",
"), default={}, ) self.last_update = int(time.time()) return self.all_notifications async def get_notifications_for_user( user, groups,",
"in [user, *groups]: # Filter out identical notifications that were already captured via",
"the user continue seen = False for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj(",
"deny operation locally under \"RoleA\" with session name = \"UserA\", so the generated",
"5), force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function,",
"redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time()) return self.all_notifications",
"not seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user = [ v for",
"in notifications_for_user if v.expiration > current_time ] # Show newest notifications first notifications_for_user",
") log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async",
"i: i.event_time, reverse=True ) # Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification",
"__init__(self): self.last_update = 0 self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh",
"performed an access deny operation locally under \"RoleA\" with session name = \"UserA\",",
"notifications_to_return: if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue unread_count +=",
"as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1: # Skip",
"ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time",
"to see 2 # notifications. notifications = all_notifications.get(user_or_group) if not notifications: continue notifications",
"> notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications:",
"or ( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications =",
"notification in notifications_to_return: if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue",
"len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l),",
"user. However, \"UserA\" is a member of \"GroupA\", which owns RoleA. We want",
"future changes to the model that may invalidate older # notifications notification =",
"continue if notification.version != 1: # Skip unsupported versions of the notification model",
"return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification",
") from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import (",
"[ v for v in notifications_for_user if v.expiration > current_time ] # Show",
"current_time ] # Show newest notifications first notifications_for_user = sorted( notifications_for_user, key=lambda i:",
"\"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count",
"redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time())",
"notifications_for_user = [] for user_or_group in [user, *groups]: # Filter out identical notifications",
"user-specific attribution. IE: \"UserA\" # performed an access deny operation locally under \"RoleA\"",
"cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\":",
"await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"]",
"Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1: #",
"in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id ):",
"= f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group",
"Dict import sentry_sdk import ujson as json from asgiref.sync import sync_to_async from consoleme.config",
"int(time.time()) return self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) ->",
") -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\": user,",
"operation locally under \"RoleA\" with session name = \"UserA\", so the generated #",
"Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user in notification.read_by_users or",
"invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\":",
"= await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification)",
"changes to the model that may invalidate older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw)",
"self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"),",
"\"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time()) return",
"if user in notification.hidden_for_users: # Skip this notification if it isn't hidden for",
"\"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update = int(time.time()) return self.all_notifications async def get_notifications_for_user( user,",
"async def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id}",
"# notifications. notifications = all_notifications.get(user_or_group) if not notifications: continue notifications = json.loads(notifications) for",
"import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log = config.get_logger() class",
"import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton",
"import sync_to_async from consoleme.config import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, )",
"which owns RoleA. We want # to show the notification to members of",
"notifications_for_user, key=lambda i: i.event_time, reverse=True ) # Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications]",
"of \"GroupA\", as well as \"UserA\" but we don't want \"UserA\" to see",
"current_time = int(time.time()) log_data = {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list)",
"UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification",
"from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton",
"from consoleme.config import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo",
"notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time",
"{ \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler()",
"v for v in notifications_for_user if v.expiration > current_time ] # Show newest",
"self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time()) -",
"user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data =",
"with session name = \"UserA\", so the generated # notification is tied to",
"GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\": user, \"max_notifications\": max_notifications,",
"v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\",",
"= notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user",
"import Dict import sentry_sdk import ujson as json from asgiref.sync import sync_to_async from",
"- self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\",",
"self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function",
"\"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() )",
"\"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get(",
") log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\":",
"= int(time.time()) return self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, )",
"sys import time from collections import defaultdict from typing import Dict import sentry_sdk",
"= True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if",
"sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str,",
"\"RoleA\" with session name = \"UserA\", so the generated # notification is tied",
"def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\"",
"= original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\"",
"# Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user",
"notifications: continue notifications = json.loads(notifications) for notification_raw in notifications: try: # We parse",
"notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k]",
"return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb =",
"\"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await",
"access deny operation locally under \"RoleA\" with session name = \"UserA\", so the",
"ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = []",
"str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1: # Skip unsupported versions of the",
"return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time =",
"for notification_raw in notifications: try: # We parse ConsoleMeUserNotification individually instead of as",
"ConsoleMeUserNotification individually instead of as an array # to account for future changes",
"\"UserA\" to see 2 # notifications. notifications = all_notifications.get(user_or_group) if not notifications: continue",
"= all_notifications.get(user_or_group) if not notifications: continue notifications = json.loads(notifications) for notification_raw in notifications:",
"retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20",
"= json.loads(notifications) for notification_raw in notifications: try: # We parse ConsoleMeUserNotification individually instead",
"if notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3(",
"notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id ): seen",
"# to show the notification to members of \"GroupA\", as well as \"UserA\"",
"ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups:",
"redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"]",
"\"UserA\" is a member of \"GroupA\", which owns RoleA. We want # to",
"# Skip this notification if it isn't hidden for the user continue seen",
") ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\"",
"individually instead of as an array # to account for future changes to",
"notifications notifications_for_user = [ v for v in notifications_for_user if v.expiration > current_time",
") from consoleme.lib.singleton import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update",
"model continue if user in notification.hidden_for_users: # Skip this notification if it isn't",
"str): ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"):",
"see 2 # notifications. notifications = all_notifications.get(user_or_group) if not notifications: continue notifications =",
"import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications",
"= ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version",
"user in notification.hidden_for_users: # Skip this notification if it isn't hidden for the",
"= UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for",
"sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True ) # Increment Unread Count notifications_to_return =",
"\"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications",
"notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), }",
"log_data = {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await",
"# We parse ConsoleMeUserNotification individually instead of as an array # to account",
"), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return {",
"a member of \"GroupA\", which owns RoleA. We want # to show the",
"that were already captured via user-specific attribution. IE: \"UserA\" # performed an access",
"for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k,",
"continue if user in notification.hidden_for_users: # Skip this notification if it isn't hidden",
"\"GroupA\", as well as \"UserA\" but we don't want \"UserA\" to see 2",
"notifications = json.loads(notifications) for notification_raw in notifications: try: # We parse ConsoleMeUserNotification individually",
"were already captured via user-specific attribution. IE: \"UserA\" # performed an access deny",
"class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications = [] async def retrieve_all_notifications(self,",
"Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user in notification.read_by_users",
"consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import",
"notifications = all_notifications.get(user_or_group) if not notifications: continue notifications = json.loads(notifications) for notification_raw in",
"import ujson as json from asgiref.sync import sync_to_async from consoleme.config import config from",
"0 self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time())",
"+= 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb =",
") self.last_update = int(time.time()) return self.all_notifications async def get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5),",
"notification_raw in notifications: try: # We parse ConsoleMeUserNotification individually instead of as an",
"1: # Skip unsupported versions of the notification model continue if user in",
"RoleA. We want # to show the notification to members of \"GroupA\", as",
"user continue seen = False for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw",
"if not notifications: continue notifications = json.loads(notifications) for notification_raw in notifications: try: #",
"identical notifications that were already captured via user-specific attribution. IE: \"UserA\" # performed",
"len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)(",
"( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await",
") unread_count = 0 notifications_for_user = [] for user_or_group in [user, *groups]: #",
"= int(time.time()) log_data = {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l",
"from collections import defaultdict from typing import Dict import sentry_sdk import ujson as",
"notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table,",
"\"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data)",
"continue seen = False for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw )",
"} current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0",
"generated # notification is tied to the user. However, \"UserA\" is a member",
"user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v",
"notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len(",
"\"expired\" notifications notifications_for_user = [ v for v in notifications_for_user if v.expiration >",
"store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import",
"notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True ) # Increment Unread Count",
"await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if",
"try: # We parse ConsoleMeUserNotification individually instead of as an array # to",
"ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version !=",
"notification.read_for_current_user = True continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async",
"20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\",",
"out \"expired\" notifications notifications_for_user = [ v for v in notifications_for_user if v.expiration",
"= True continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def",
"to account for future changes to the model that may invalidate older #",
"= 0 self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or (",
"Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]:",
"\"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh",
"session name = \"UserA\", so the generated # notification is tied to the",
"consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse,",
"seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user = [ v for v",
"as \"UserA\" but we don't want \"UserA\" to see 2 # notifications. notifications",
"= defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in all_notifications_l:",
"sync_to_async from consoleme.config import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from",
"\"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications = await",
"already captured via user-specific attribution. IE: \"UserA\" # performed an access deny operation",
"all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for",
"the user. However, \"UserA\" is a member of \"GroupA\", which owns RoleA. We",
"notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\",",
"async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)( Item=ddb._data_to_dynamo_replace(notification.dict()) ) await cache_notifications_to_redis_s3()",
"sentry_sdk import ujson as json from asgiref.sync import sync_to_async from consoleme.config import config",
"from asgiref.sync import sync_to_async from consoleme.config import config from consoleme.lib.cache import ( retrieve_json_data_from_redis_or_s3,",
"config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications = [] async def",
"reverse=True ) # Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return:",
"= {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table)",
"versions of the notification model continue if user in notification.hidden_for_users: # Skip this",
"We parse ConsoleMeUserNotification individually instead of as an array # to account for",
"): seen = True if not seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications",
"= len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification:",
"# Filter out \"expired\" notifications notifications_for_user = [ v for v in notifications_for_user",
"the generated # notification is tied to the user. However, \"UserA\" is a",
"notification.read_by_all: notification.read_for_current_user = True continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count )",
"or notification.read_by_all: notification.read_for_current_user = True continue unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count",
"if notification.version != 1: # Skip unsupported versions of the notification model continue",
"consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log = config.get_logger()",
"hidden for the user continue seen = False for existing_user_notification_raw in notifications_for_user: existing_user_notification",
"json as original_json import sys import time from collections import defaultdict from typing",
"notification.hidden_for_users: # Skip this notification if it isn't hidden for the user continue",
"# to account for future changes to the model that may invalidate older",
"write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)( Item=ddb._data_to_dynamo_replace(notification.dict()) ) await cache_notifications_to_redis_s3() return True",
"account for future changes to the model that may invalidate older # notifications",
"unsupported versions of the notification model continue if user in notification.hidden_for_users: # Skip",
"ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id ): seen = True if",
"notifications_for_user[0:max_notifications] for notification in notifications_to_return: if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user =",
"ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time())",
"async def cache_notifications_to_redis_s3() -> Dict[str, int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data",
"function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\":",
"consoleme.lib.singleton import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0",
"not notifications: continue notifications = json.loads(notifications) for notification_raw in notifications: try: # We",
"in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v in",
"except Exception as e: log.error({**log_data, \"error\": str(e)}) sentry_sdk.capture_exception() continue if notification.version != 1:",
"user_or_group in [user, *groups]: # Filter out identical notifications that were already captured",
"from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log =",
"existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id",
"retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, ) self.last_update =",
"ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return",
"for user_or_group in [user, *groups]: # Filter out identical notifications that were already",
"We want # to show the notification to members of \"GroupA\", as well",
"= await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"]) async def cache_notifications_to_redis_s3()",
"1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb = UserDynamoHandler()",
"Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self): self.last_update = 0 self.all_notifications =",
"all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user = [] for",
"[] for user_or_group in [user, *groups]: # Filter out identical notifications that were",
"but we don't want \"UserA\" to see 2 # notifications. notifications = all_notifications.get(user_or_group)",
"so the generated # notification is tied to the user. However, \"UserA\" is",
"= ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id ): seen = True",
"if changed_notifications: ddb.parallel_write_table(ddb.notifications_table, changed_notifications) if notifications_by_user_group: for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] =",
"= \"UserA\", so the generated # notification is tied to the user. However,",
"Skip unsupported versions of the notification model continue if user in notification.hidden_for_users: #",
"# notification is tied to the user. However, \"UserA\" is a member of",
"attribution. IE: \"UserA\" # performed an access deny operation locally under \"RoleA\" with",
"for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id ==",
") if ( notification.predictable_id == existing_user_notification.predictable_id ): seen = True if not seen:",
"changed_notifications = [] for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time >",
"get_notifications_for_user( user, groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data",
"notifications first notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True ) # Increment",
"} async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)( Item=ddb._data_to_dynamo_replace(notification.dict()) ) await",
"to show the notification to members of \"GroupA\", as well as \"UserA\" but",
"def __init__(self): self.last_update = 0 self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False): if",
"don't want \"UserA\" to see 2 # notifications. notifications = all_notifications.get(user_or_group) if not",
"max_notifications, \"force_refresh\": force_refresh, } current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh )",
"for future changes to the model that may invalidate older # notifications notification",
"# Skip unsupported versions of the notification model continue if user in notification.hidden_for_users:",
"= True if not seen: notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user =",
"[] for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired",
"import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification, GetNotificationsForUserResponse, )",
"name = \"UserA\", so the generated # notification is tied to the user.",
") # Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for notification in notifications_to_return: if",
"v in notifications_for_user if v.expiration > current_time ] # Show newest notifications first",
"int(time.time()) log_data = {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group = defaultdict(list) all_notifications_l =",
"for notification in notifications_to_return: if user in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True",
"the notification to members of \"GroupA\", as well as \"UserA\" but we don't",
"*groups]: # Filter out identical notifications that were already captured via user-specific attribution.",
"original_json import sys import time from collections import defaultdict from typing import Dict",
"of the notification model continue if user in notification.hidden_for_users: # Skip this notification",
"k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"),",
"it isn't hidden for the user continue seen = False for existing_user_notification_raw in",
"= [] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or ( int(time.time()) - self.last_update",
"ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def",
"function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\": function} ddb = UserDynamoHandler()",
"members of \"GroupA\", as well as \"UserA\" but we don't want \"UserA\" to",
"= await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user = [] for user_or_group",
"= UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\": notification_id} ) if notification.get(\"Item\"): return ConsoleMeUserNotification.parse_obj(notification[\"Item\"])",
"Filter out \"expired\" notifications notifications_for_user = [ v for v in notifications_for_user if",
"int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3(",
"first notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True ) # Increment Unread",
"typing import Dict import sentry_sdk import ujson as json from asgiref.sync import sync_to_async",
"unread_count += 1 return GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb",
"<gh_stars>1000+ import json as original_json import sys import time from collections import defaultdict",
"for v in notifications_for_user if v.expiration > current_time ] # Show newest notifications",
"unread_count = 0 notifications_for_user = [] for user_or_group in [user, *groups]: # Filter",
"original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ),",
"\"UserA\" # performed an access deny operation locally under \"RoleA\" with session name",
"= await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get( \"notifications.s3.key\", \"notifications/all_notifications_v1.json.gz\" ), default={}, )",
"def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)( Item=ddb._data_to_dynamo_replace(notification.dict()) ) await cache_notifications_to_redis_s3() return",
"under \"RoleA\" with session name = \"UserA\", so the generated # notification is",
"current_time > notification.expiration: notification.expired = True changed_notifications.append(notification.dict()) for user_or_group in notification.users_or_groups: notifications_by_user_group[user_or_group].append(notification.dict()) if",
"import ( retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder",
"all_notifications.get(user_or_group) if not notifications: continue notifications = json.loads(notifications) for notification_raw in notifications: try:",
"force_refresh, } current_time = int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count =",
"groups, max_notifications=config.get(\"get_notifications_for_user.max_notifications\", 5), force_refresh=False, ) -> GetNotificationsForUserResponse: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = {",
"show the notification to members of \"GroupA\", as well as \"UserA\" but we",
"in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"),",
"notification.predictable_id == existing_user_notification.predictable_id ): seen = True if not seen: notifications_for_user.append(notification) # Filter",
") async def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification = await sync_to_async(ddb.notifications_table.get_item)( Key={\"predictable_id\":",
"existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if ( notification.predictable_id == existing_user_notification.predictable_id ): seen =",
"= [] for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration:",
"notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"), s3_key=config.get(",
"owns RoleA. We want # to show the notification to members of \"GroupA\",",
"array # to account for future changes to the model that may invalidate",
"log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb",
"defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in all_notifications_l: notification",
"json.loads(notifications) for notification_raw in notifications: try: # We parse ConsoleMeUserNotification individually instead of",
"GetNotificationsForUserResponse( notifications=notifications_to_return, unread_count=unread_count ) async def fetch_notification(notification_id: str): ddb = UserDynamoHandler() notification =",
"\"num_notifications\": len(all_notifications_l), } async def write_notification(notification: ConsoleMeUserNotification): ddb = UserDynamoHandler() await sync_to_async(ddb.notifications_table.put_item)( Item=ddb._data_to_dynamo_replace(notification.dict())",
"this notification if it isn't hidden for the user continue seen = False",
"member of \"GroupA\", which owns RoleA. We want # to show the notification",
"for the user continue seen = False for existing_user_notification_raw in notifications_for_user: existing_user_notification =",
"force_refresh=False): if force_refresh or ( int(time.time()) - self.last_update > config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 )",
"( ConsoleMeUserNotification, GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton):",
"in notification.read_by_users or notification.read_by_all: notification.read_for_current_user = True continue unread_count += 1 return GetNotificationsForUserResponse(",
"RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user = [] for user_or_group in [user,",
"\"UserA\", so the generated # notification is tied to the user. However, \"UserA\"",
"key=lambda i: i.event_time, reverse=True ) # Increment Unread Count notifications_to_return = notifications_for_user[0:max_notifications] for",
"log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()),",
"retrieve_json_data_from_redis_or_s3, store_json_results_in_redis_and_s3, ) from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models",
"self.last_update = 0 self.all_notifications = [] async def retrieve_all_notifications(self, force_refresh=False): if force_refresh or",
"\"notifications/all_notifications_v1.json.gz\" ), ) log_data[\"num_user_groups_for_notifications\"] = len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return",
"notifications_by_user_group = defaultdict(list) all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table) changed_notifications = [] for existing_notification in",
"in notification.hidden_for_users: # Skip this notification if it isn't hidden for the user",
"IE: \"UserA\" # performed an access deny operation locally under \"RoleA\" with session",
"for existing_notification in all_notifications_l: notification = ConsoleMeUserNotification.parse_obj(existing_notification) if current_time > notification.expiration: notification.expired =",
"int]: function = f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\": function} ddb =",
"f\"{__name__}.{sys._getframe().f_code.co_name}\" current_time = int(time.time()) log_data = {\"function\": function} ddb = UserDynamoHandler() notifications_by_user_group =",
"= f\"{__name__}.{sys._getframe().f_code.co_name}\" log_data = { \"function\": function, \"user\": user, \"max_notifications\": max_notifications, \"force_refresh\": force_refresh,",
"as json from asgiref.sync import sync_to_async from consoleme.config import config from consoleme.lib.cache import",
"[user, *groups]: # Filter out identical notifications that were already captured via user-specific",
"is tied to the user. However, \"UserA\" is a member of \"GroupA\", which",
"> current_time ] # Show newest notifications first notifications_for_user = sorted( notifications_for_user, key=lambda",
"= len( notifications_by_user_group.keys() ) log_data[\"num_notifications\"] = len(all_notifications_l) log.debug(log_data) return { \"num_user_groups_to_notify\": len(notifications_by_user_group.keys()), \"num_notifications\":",
"from consoleme.lib.dynamo import UserDynamoHandler from consoleme.lib.json_encoder import SetEncoder from consoleme.lib.notifications.models import ( ConsoleMeUserNotification,",
"int(time.time()) all_notifications = await RetrieveNotifications().retrieve_all_notifications( force_refresh ) unread_count = 0 notifications_for_user = []",
"if ( notification.predictable_id == existing_user_notification.predictable_id ): seen = True if not seen: notifications_for_user.append(notification)",
"older # notifications notification = ConsoleMeUserNotification.parse_obj(notification_raw) except Exception as e: log.error({**log_data, \"error\": str(e)})",
"as an array # to account for future changes to the model that",
"notifications that were already captured via user-specific attribution. IE: \"UserA\" # performed an",
"GetNotificationsForUserResponse, ) from consoleme.lib.singleton import Singleton log = config.get_logger() class RetrieveNotifications(metaclass=Singleton): def __init__(self):",
"newest notifications first notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True ) #",
"notifications_for_user.append(notification) # Filter out \"expired\" notifications notifications_for_user = [ v for v in",
"config.get( \"get_notifications_for_user.notification_retrieval_interval\", 20 ) ): self.all_notifications = await retrieve_json_data_from_redis_or_s3( redis_key=config.get(\"notifications.redis_key\", \"ALL_NOTIFICATIONS\"), redis_data_type=\"hash\", s3_bucket=config.get(\"notifications.s3.bucket\"),",
"= False for existing_user_notification_raw in notifications_for_user: existing_user_notification = ConsoleMeUserNotification.parse_obj( existing_user_notification_raw ) if (",
"for k, v in notifications_by_user_group.items(): notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder) await store_json_results_in_redis_and_s3( notifications_by_user_group, redis_key=config.get(\"notifications.redis_key\",",
"Show newest notifications first notifications_for_user = sorted( notifications_for_user, key=lambda i: i.event_time, reverse=True )"
] |
[
"a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose: self.verbose",
"sample. Samples are run as background processes for parallelization.\\n\".format( self.n_cores ) ) if",
"sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent,",
"run as background processes for parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict =",
"class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent = silent",
"from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface",
"output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'}",
"= _use_n_cores(n_cores) print( \"\\tnote... this is {} cores per sample. Samples are run",
"outfile self.outdir = os.path.dirname(self.outfile) if not title: title = self.outdir else: title =",
"multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir)",
"n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if",
"-b {} -o {} -p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self,",
"verbose self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path,",
"\"multiBigwigSummary bins -b {} -o {} -p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable)",
"self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o {} -p {}\".format( bigwigs, outfile, self.n_cores",
"def load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path,",
"import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools:",
"_use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def",
"_find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path, sample_dirname=False, silent=False): if",
"= verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is {} cores per sample.",
"is {} cores per sample. Samples are run as background processes for parallelization.\\n\".format(",
"if BamDict: self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage",
"sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ):",
"load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\",",
"bamCoverage command issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable",
"self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\",",
"if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile",
"print( \"\\tnote... this is {} cores per sample. Samples are run as background",
"outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw -p {}",
"{} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False, silent=False): if",
"_use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o {} -p {}\".format( bigwigs, outfile,",
"supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose:",
"BamDict: self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command",
"issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage",
"-b {} -o {}.bw -p {} -of bigwig &\".format( bamfile, outprefix, n_cores )",
"as background processes for parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict = BamDict",
"&\".format( bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools",
"not title: title = self.outdir else: title = os.path.join(self.outdir, title) _plotCorrelation(title, self.outfile, silent)",
"silent=silent, ) ) def load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent",
"silent=silent, ) ) def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If",
"dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is",
"n_cores=2 ): \"\"\"If supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken as",
"verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent = silent self.verbose = verbose self.DataDict =",
"if not title: title = self.outdir else: title = os.path.join(self.outdir, title) _plotCorrelation(title, self.outfile,",
"sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {}",
"__init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent = silent self.verbose = verbose",
"= os.path.dirname(self.outfile) if not title: title = self.outdir else: title = os.path.join(self.outdir, title)",
"{}.bw -p {} -of bigwig &\".format( bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable,",
"if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) )",
"os # local imports # # ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from",
"<filename>vintools/_tools/_deepTools/_deepTools_Module.py # package imports # # --------------- # import os # local imports",
"self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self,",
"self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile",
"{} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent =",
") ) if BamDict: self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run:",
") def load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files(",
"sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent,",
"background processes for parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict = BamDict if",
"= silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self,",
"bigwig &\".format( bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose:",
"not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile in",
"\"\"\"If supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if",
"= verbose self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def load_bams(self,",
"if verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is {}",
"self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False, silent=False): if silent:",
"summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not title:",
") os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile self.outdir",
"{}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file:",
"_find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False,",
"imports # # --------------- # import os # local imports # # -------------",
"print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False",
"= \"multiBigwigSummary bins -b {} -o {} -p {}\".format( bigwigs, outfile, self.n_cores )",
"verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken",
"{} -p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False):",
"in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw",
"from deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs",
"of deepTools\"\"\" self.silent = silent self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"] =",
"silent=False): if summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not title: title",
"= outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values()))",
"format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose: self.verbose = verbose self.n_cores",
"command issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable =",
"command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs",
"BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample,",
"# # --------------- # import os # local imports # # ------------- #",
"{'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose: self.verbose = verbose self.n_cores =",
"from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self,",
"this is {} cores per sample. Samples are run as background processes for",
"deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs =",
"\"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from",
"self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not title: title = self.outdir else:",
"self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self, BamDict=False, output_dir=\"./\",",
"_find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent",
"# local imports # # ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir",
"def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent = silent self.verbose =",
"processes for parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict = BamDict if not",
"self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir =",
"outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command",
"..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False,",
"imports # # ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir",
"\"bamCoverage -b {} -o {}.bw -p {} -of bigwig &\".format( bamfile, outprefix, n_cores",
"-p {} -of bigwig &\".format( bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\")",
"taken as input\"\"\" if verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote...",
"bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {} -o",
"if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable =",
"silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, )",
"silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def",
"if summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not title: title =",
"if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix =",
"= os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores)",
"sample) self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw -p {} -of bigwig &\".format(",
"..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class",
"_flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix",
"package imports # # --------------- # import os # local imports # #",
"sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent =",
"\"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile",
"silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path, sample_dirname=False,",
"interface of deepTools\"\"\" self.silent = silent self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"]",
"= outfile self.outdir = os.path.dirname(self.outfile) if not title: title = self.outdir else: title",
"_flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b",
"path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname,",
"load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\",",
"bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage",
"._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of",
"verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is {} cores",
"_use_n_cores(n_cores) print( \"\\tnote... this is {} cores per sample. Samples are run as",
"): \"\"\"If supplied, a dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\"",
"silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, )",
"self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is {} cores per sample. Samples are",
"def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile)",
"silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self, BamDict=False,",
"self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \"",
"issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary",
"Samples are run as background processes for parallelization.\\n\".format( self.n_cores ) ) if BamDict:",
"_flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook",
"os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable",
"\"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def",
"silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent = silent self.verbose = verbose self.DataDict",
") if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\")",
"# package imports # # --------------- # import os # local imports #",
"def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile",
"outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile)",
"import os # local imports # # ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores",
"path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname,",
"BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary of format: {'sample':",
"bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary of",
") def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a",
"\" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o {}",
"dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir,",
"parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir)",
"input\"\"\" if verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is",
"_deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent = silent self.verbose",
"= \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o",
"self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path, sample_dirname=False, silent=False):",
"summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not title: title = self.outdir",
"print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\"",
"bins -b {} -o {} -p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def",
"self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary of format:",
"{} def load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files(",
"are run as background processes for parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict",
"as input\"\"\" if verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this",
"bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {}",
"file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent",
"self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage(",
"n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command issued:\",",
"--------------- # import os # local imports # # ------------- # from ..._utilities._system_utils._use_n_cores",
"self.outdir = os.path.dirname(self.outfile) if not title: title = self.outdir else: title = os.path.join(self.outdir,",
"def load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path,",
"self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o {} -p {}\".format(",
"def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied, a dictionary",
"if silent: self.silent = silent self.DataDict[\"bigwigs\"].update( _find_sample_files( path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) )",
"from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation",
"os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile =",
"import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False):",
"self.silent = silent self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"]",
"silent: self.silent = silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def",
"file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2",
"for parallelization.\\n\".format( self.n_cores ) ) if BamDict: self.BamDict = BamDict if not os.path.exists(output_dir):",
"= _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o {} -p {}\".format( bigwigs,",
"self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw -p",
"os.path.dirname(self.outfile) if not title: title = self.outdir else: title = os.path.join(self.outdir, title) _plotCorrelation(title,",
"os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile in self.BamDict.items():",
"# from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import _find_sample_files,",
"-of bigwig &\".format( bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if",
"cores per sample. Samples are run as background processes for parallelization.\\n\".format( self.n_cores )",
"\"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir):",
"bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ):",
"# ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions",
"of format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose: self.verbose = verbose",
"-o {} -p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False,",
"= \"bamCoverage -b {} -o {}.bw -p {} -of bigwig &\".format( bamfile, outprefix,",
"= {} def load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bams\"].update(",
") if BamDict: self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools",
"local imports # # ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import",
"plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if",
"self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent",
"bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile",
") ) def load_bw(self, path, sample_dirname=False, silent=False): if silent: self.silent = silent self.DataDict[\"bigwigs\"].update(",
"= silent self.DataDict[\"bams\"].update( _find_sample_files( path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path,",
"print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable)",
"else: if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary(",
"verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is {} cores per sample. Samples",
"print(\"deepTools bamCoverage command issued:\\n\") for sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample)",
"os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins",
"path, file_extension=\"bw\", sample_dir_level=sample_dirname, silent=silent, ) ) def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False,",
"import _find_sample_files, _plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\"",
"self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw -p {} -of bigwig &\".format( bamfile,",
"outfile self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores",
"): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not",
"\"\\tnote... this is {} cores per sample. Samples are run as background processes",
"dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\")",
"{} -o {}.bw -p {} -of bigwig &\".format( bamfile, outprefix, n_cores ) if",
"self.n_cores ) ) if BamDict: self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if",
") ) def bamCoverage( self, BamDict=False, output_dir=\"./\", dry_run=False, verbose=False, n_cores=2 ): \"\"\"If supplied,",
"{} cores per sample. Samples are run as background processes for parallelization.\\n\".format( self.n_cores",
"\"\"\"Notebook interface of deepTools\"\"\" self.silent = silent self.verbose = verbose self.DataDict = {}",
"per sample. Samples are run as background processes for parallelization.\\n\".format( self.n_cores ) )",
"os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw -p {} -of bigwig",
"= BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\") for",
"-o {}.bw -p {} -of bigwig &\".format( bamfile, outprefix, n_cores ) if dry_run:",
"multiBigwigsummary( self, outfile=\"multiBigwigsummary.results.npz\", n_cores=False ): \"\"\"runs multiBigwigsummary from deepTools.\"\"\" self.outfile = outfile self.outdir",
"self.outdir = os.path.dirname(self.outfile) if not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores =",
"is taken as input\"\"\" if verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print(",
"{} -of bigwig &\".format( bamfile, outprefix, n_cores ) if dry_run: print(self.bamCoverage_executable, \"\\n\") else:",
"silent self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {}",
"# # ------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from",
"_plotCorrelation class _deepTools: def __init__(self, silent=False, verbose=False): \"\"\"Notebook interface of deepTools\"\"\" self.silent =",
"------------- # from ..._utilities._system_utils._use_n_cores import _use_n_cores from ..._utilities._system_utils._flexible_mkdir import _flexible_mkdir from ._deepTools_supporting_functions import",
"= {} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False, silent=False): if silent: self.silent",
"title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile self.outdir = os.path.dirname(self.outfile) if not",
"os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile = outfile self.outdir =",
"self.verbose = verbose self.n_cores = _use_n_cores(n_cores) print( \"\\tnote... this is {} cores per",
"\".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary bins -b {} -o {} -p",
"outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if summary_results_file: self.outfile =",
"if dry_run: print(self.bamCoverage_executable, \"\\n\") else: if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable,",
"self.BamDict = BamDict if not os.path.exists(output_dir): _flexible_mkdir(output_dir) if dry_run: print(\"deepTools bamCoverage command issued:\\n\")",
"path, file_extension=\"bam\", sample_dir_level=sample_dirname, silent=silent, ) ) def load_bw(self, path, sample_dirname=False, silent=False): if silent:",
"{} -o {} -p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False,",
"self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def",
"self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False,",
"= os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b {} -o {}.bw -p {} -of",
"= silent self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] =",
"deepTools\"\"\" self.silent = silent self.verbose = verbose self.DataDict = {} self.DataDict[\"bams\"] = {}",
"dictionary of format: {'sample': '/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose: self.verbose =",
"'/path/to/sample/sample.bam'} is taken as input\"\"\" if verbose: self.verbose = verbose self.n_cores = _use_n_cores(n_cores)",
"for sample, bamfile in self.BamDict.items(): outprefix = os.path.join(output_dir, sample) self.bamCoverage_executable = \"bamCoverage -b",
"if self.verbose: print(\"deepTools bamCoverage command issued:\", \"\\n\") print(self.bamCoverage_executable, \"\\n\") os.system(self.bamCoverage_executable) def multiBigwigsummary( self,",
"= {} self.DataDict[\"bams\"] = {} self.DataDict[\"bigwigs\"] = {} def load_bams(self, path, sample_dirname=False, silent=False):",
"-p {}\".format( bigwigs, outfile, self.n_cores ) os.system(self.multiBigwigsummary_executable) def plotCorrelation(self, title=False, summary_results_file=False, silent=False): if",
"# import os # local imports # # ------------- # from ..._utilities._system_utils._use_n_cores import",
"# --------------- # import os # local imports # # ------------- # from",
"not os.path.exists(self.outdir): _flexible_mkdir(self.outdir) bigwigs = \" \".join(list(self.DataDict[\"bigwigs\"].values())) self.n_cores = _use_n_cores(n_cores) self.multiBigwigsummary_executable = \"multiBigwigSummary"
] |
[
"body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned error: ' + body['reason']) return body['result']",
"tuple (Code, Headers, Body) \"\"\" protocol = 'https' if use_ssl else 'http' response",
"times. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body =",
"== 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) for i in range(len(body['result'])):",
"returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT):",
"True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned",
"if rest endpoints were requested in given order. Returns True or False. The",
"timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of any messages has been received on",
"return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance",
"(by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path,",
"the function to return full msg history upon success. \"\"\" start_time = time.time()",
"True, '') body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error:",
"were requested in given order. Returns True or False. The expected_history is a",
"def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to send given message to",
"request to an appmock instance to check how many clients are connected to",
"g. counters will be reset. Existing connections WILL NOT BE DISTURBED. \"\"\" _,",
"return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many times",
"restarted clean. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body",
"return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given",
"tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of connections are established",
"'path': endpoint_path } _, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body",
"given number of any messages has been received on given port, or after",
"or more connections than expected. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while",
"body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when",
"class AppmockClient(object): def __init__(self, ip): self.ip = ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self,",
"return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of specific messages has been received",
"Appmock remote control port appmock_rc_port = 9999 # These defines determine how often",
"= 9999 # These defines determine how often the appmock server will be",
"path, use_ssl, data): \"\"\" Helper function that perform a HTTP GET request Returns",
"as in app_desc module, for example: '/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port,",
"'error': raise Exception('tcp_server_send returned error: ' + body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port):",
"_port } } return entry json_data = [create_endpoint_entry(port, path) for (port, path) in",
"+ body['reason']) for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip):",
"how many times has given endpoint been requested. IMPORTANT: the endpoint_path must be",
"tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all messages that has",
"instance to check how many clients are connected to given endpoint (by port).",
"250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip):",
"start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary)",
"there is the same or more messages than expected. The return_history flag causes",
"the appmock server will be requested # to check for condition when waiting",
"module, for example: '/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port, 'path': endpoint_path }",
"to return full msg history upon success. \"\"\" start_time = time.time() wait_for =",
"raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE",
"time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip,",
"\"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port)",
"timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of connections are established on given port,",
"because # this fun might be used for benchmarking. if return_history: return tcp_server_history(appmock_ip,",
"self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def",
"body['reason']) for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\"",
"'port': _port } } return entry json_data = [create_endpoint_entry(port, path) for (port, path)",
"reset_rest_history(appmock_ip): \"\"\" Performs a request to an appmock instance to reset all the",
"error: ' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT):",
"returned error: ' + body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a",
"_http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise",
"== 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) return body['result'] def tcp_server_history(appmock_ip,",
"body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body) if body['result'] ==",
"NOT BE DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '')",
"messages that has been received by the TCP server mock. \"\"\" path =",
"number_of_connections: return elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned error:",
"= tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >= msg_count: break elif result ==",
"def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number",
"given endpoint. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body",
"> timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) #",
"'reset_rest_history returned error: ' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\"",
"json_data = [create_endpoint_entry(port, path) for (port, path) in expected_history] _, _, body =",
"for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry = {",
"ip): self.ip = ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return",
"to an appmock instance to check how many clients are connected to given",
"return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def",
"given number of specific messages has been received on given port, or after",
"makes the function succeed when there is the same or more messages than",
"True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned",
"\"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body)",
"more connections than expected. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True:",
"port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class",
"to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings()",
"return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip,",
"elif result == number_of_connections: return elif time.time() - start_time > timeout_sec: raise Exception(",
"def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False,",
"'') body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned error:",
"Returns when given number of specific messages has been received on given port,",
"timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many",
"expected. The return_history flag causes the function to return full msg history upon",
"connected to given endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body",
"msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return",
"the same as if it was restarted clean. \"\"\" _, _, body =",
"(port, path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry",
"def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of connections",
"def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return",
"amount of times. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _,",
"= '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body",
"def __init__(self, client, port): self.client = client self.ip = client.ip self.port = port",
"for (port, path) in expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True,",
"upon success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result =",
"MIT license cited in 'LICENSE.txt' Client library to contact appmock instances. \"\"\" import",
"msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port, path, use_ssl, data): \"\"\" Helper function",
"function succeed when there is the same or more messages than expected. The",
"send given message to all connected clients, given amount of times. \"\"\" encoded_message",
"instance to reset all the history connected with ALL mocked rest endpoints. The",
"reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client = client self.ip",
"Returns number of all messages that has been received by the TCP server",
"import time import requests # Appmock remote control port appmock_rc_port = 9999 #",
"contact appmock instances. \"\"\" import base64 import json import time import requests #",
"'{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip,",
"def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec)",
"= { 'port': endpoint_port, 'path': endpoint_path } _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"an appmock instance to check how many clients are connected to given endpoint",
"body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if body['result'] ==",
"return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec)",
"time.sleep(wait_for / 1000.0) # No incrementing wait time here because # this fun",
"timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of specific messages has been received on",
"accept_more flag makes the function succeed when there is the same or more",
"error: ' + body['reason']) for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result']",
"in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request",
"TCP endpoints. The reset will cause this instance to act the same as",
"e. g. counters will be reset. Existing connections WILL NOT BE DISTURBED. \"\"\"",
"_http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if body['result'] == 'error': raise",
"Client library to contact appmock instances. \"\"\" import base64 import json import time",
"__init__(self, ip): self.ip = ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self):",
"appmock server will be requested # to check for condition when waiting for",
"given message, that has been received by the TCP server mock. \"\"\" encoded_message",
"tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of any messages",
"appmock instance to obtain full history of messages received on given endpoint. \"\"\"",
"counters will be reset. Existing connections WILL NOT BE DISTURBED. \"\"\" _, _,",
"example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry = { 'endpoint':",
"endpoint. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body =",
"next interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT =",
"start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout') else: time.sleep(wait_for / 1000.0)",
"json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned error:",
"be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class",
"connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1):",
"flag causes the function to return full msg history upon success. \"\"\" start_time",
"= '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body =",
"= time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more",
"or after it timeouts. The accept_more flag makes the function succeed when there",
"body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if body['result'] ==",
"_http_post(ip, port, path, use_ssl, data): \"\"\" Helper function that perform a HTTP GET",
"msg_count: break elif result == msg_count: break elif time.time() - start_time > timeout_sec:",
"'rest_endpoint_request_count returned error: ' + body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies",
"body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock",
"port appmock_rc_port = 9999 # These defines determine how often the appmock server",
"be used for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary,",
"= json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason'])",
"' + body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to",
"This software is released under the MIT license cited in 'LICENSE.txt' Client library",
"self.port = port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return",
"when there is the same or more messages than expected. The return_history flag",
"- e. g. counters will be reset. Existing connections WILL NOT BE DISTURBED.",
"if accept_more and result >= msg_count: break elif result == msg_count: break elif",
"WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def",
"tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip)",
"data): \"\"\" Helper function that perform a HTTP GET request Returns a tuple",
"' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT):",
"'tcp_server_connection_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False,",
"a tuple (Code, Headers, Body) \"\"\" protocol = 'https' if use_ssl else 'http'",
"\"\"\" Returns when given number of connections are established on given port, or",
"obtain full history of messages received on given endpoint. \"\"\" _, _, body",
"raise Exception('tcp_server_send returned error: ' + body['reason']) for i in range(len(body['result'])): body['result'][i] =",
"instance to act the same as if it was restarted clean. \"\"\" _,",
"'port': endpoint_port, 'path': endpoint_path } _, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True,",
"body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns",
"returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False,",
"of times. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body",
"expected_history): \"\"\" Verifies if rest endpoints were requested in given order. Returns True",
"of tuples (port, path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port,",
"remote control port appmock_rc_port = 9999 # These defines determine how often the",
"'') body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error: '",
"reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client = client self.ip = client.ip",
"it timeouts. The accept_more flag makes the function succeed when there is the",
"\"\"\" Returns how many times has given endpoint been requested. IMPORTANT: the endpoint_path",
"'error': raise Exception( 'tcp_server_all_messages_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip,",
"timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *=",
"\"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip,",
"'endpoint': { 'path': _path, 'port': _port } } return entry json_data = [create_endpoint_entry(port,",
"raise Exception('tcp_server_send returned error: ' + body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\"",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned error: ' +",
"' + body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints",
"raise Exception( 'rest_endpoint_request_count returned error: ' + body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history):",
"' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns",
"each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT",
"path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry =",
"timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT):",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if",
"all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip,",
"requested. IMPORTANT: the endpoint_path must be literally the same as in app_desc module,",
"json.loads(body) if body['result'] == 'error': raise Exception( 'reset_rest_history returned error: ' + body['reason'])",
"tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of",
"= time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if",
"return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object):",
"ACK CYFRONET AGH This software is released under the MIT license cited in",
"wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history,",
"raise Exception( 'reset_rest_history returned error: ' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port,",
"== msg_count: break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned",
"tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to send given",
"request Returns a tuple (Code, Headers, Body) \"\"\" protocol = 'https' if use_ssl",
"True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_rest_history returned",
"connections than expected. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result",
"wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def",
"timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False,",
"for condition when waiting for something. # Increment rate causes each next interval",
"{ 'path': _path, 'port': _port } } return entry json_data = [create_endpoint_entry(port, path)",
"how often the appmock server will be requested # to check for condition",
"'error': raise Exception( 'expected history does not match: ' + str(body['history'])) return body['result']",
"number of any messages has been received on given port, or after it",
"accept_more, return_history, timeout_sec) def _http_post(ip, port, path, use_ssl, data): \"\"\" Helper function that",
"server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body =",
"body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number",
"+ body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to an",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned error: ' +",
"\"\"\" Returns number of messages exactly matching given message, that has been received",
"return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT):",
"True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned",
"+ body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of messages",
"rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many times has given endpoint been requested.",
"2015 ACK CYFRONET AGH This software is released under the MIT license cited",
"how many clients are connected to given endpoint (by port). \"\"\" path =",
"license cited in 'LICENSE.txt' Client library to contact appmock instances. \"\"\" import base64",
"times has given endpoint been requested. IMPORTANT: the endpoint_path must be literally the",
"\"\"\" protocol = 'https' if use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip,",
"raise Exception( 'expected history does not match: ' + str(body['history'])) return body['result'] def",
"requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip = ip def tcp_endpoint(self, port): return",
"when given number of connections are established on given port, or after it",
"return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port, path, use_ssl,",
"= base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True,",
"server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path,",
"to reset all the history connected with ALL mocked TCP endpoints. The reset",
"== 'error': raise Exception( 'reset_tcp_history returned error: ' + body['reason']) return body['result'] def",
"1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip = ip",
"return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request to an appmock instance to",
"the TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip,",
"messages than expected. The return_history flag causes the function to return full msg",
"} _, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body)",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned error: '",
"= '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body =",
"msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections,",
"The expected_history is a list of tuples (port, path), for example: [(8080, '/test1/[:binding]'),",
"message_binary) if accept_more and result >= msg_count: break elif result == msg_count: break",
"is a list of tuples (port, path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')]",
"tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of specific",
"by the TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _,",
"def __init__(self, ip): self.ip = ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def",
"time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more",
"condition when waiting for something. # Increment rate causes each next interval to",
"timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count,",
"mocked rest endpoints. The reset will cause this instance to act the same",
"(C) 2015 ACK CYFRONET AGH This software is released under the MIT license",
"TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a",
"error: ' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request",
"self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1,",
"json.loads(body) if body['result'] == 'error': raise Exception( 'reset_tcp_history returned error: ' + body['reason'])",
"established on given port, or after it timeouts. The accept_more flag makes the",
"return elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout')",
"Returns True or False. The expected_history is a list of tuples (port, path),",
"= 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self,",
"False. The expected_history is a list of tuples (port, path), for example: [(8080,",
"_, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if body['result']",
"it was restarted clean. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True,",
"exactly matching given message, that has been received by the TCP server mock.",
"is the same or more connections than expected. \"\"\" start_time = time.time() wait_for",
"message, that has been received by the TCP server mock. \"\"\" encoded_message =",
"response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many times has given",
"json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception( 'expected history does",
"time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and",
"1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\"",
"send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False,",
"Exception( 'tcp_server_connection_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1,",
"Returns when given number of connections are established on given port, or after",
"of any messages has been received on given port, or after it timeouts.",
"elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout') else:",
"a list of tuples (port, path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\"",
"the history connected with ALL mocked TCP endpoints. The reset will cause this",
"tcp_port) if accept_more and result >= number_of_connections: return elif result == number_of_connections: return",
"Returns number of messages exactly matching given message, that has been received by",
"connections WILL NOT BE DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history',",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'expected history does not",
"history upon success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result",
"instance to obtain full history of messages received on given endpoint. \"\"\" _,",
"= _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body) if body['result'] == 'error':",
"body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance to",
"base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an appmock instance",
"number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1,",
"- start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout') else: time.sleep(wait_for /",
"== 'error': raise Exception( 'expected history does not match: ' + str(body['history'])) return",
"all the history connected with ALL mocked rest endpoints. The reset will cause",
"_, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body) if body['result']",
"_path, 'port': _port } } return entry json_data = [create_endpoint_entry(port, path) for (port,",
"tcp_port): \"\"\" Returns number of all messages that has been received by the",
"'expected history does not match: ' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\"",
"to send given message to all connected clients, given amount of times. \"\"\"",
"json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) return",
"with ALL mocked TCP endpoints. The reset will cause this instance to act",
"under the MIT license cited in 'LICENSE.txt' Client library to contact appmock instances.",
"in app_desc module, for example: '/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port, 'path':",
"# Increment rate causes each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250",
"self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port) def send(self,",
">= number_of_connections: return elif result == number_of_connections: return elif time.time() - start_time >",
"if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned error: ' + body['reason']) return",
"appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send",
"= base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an appmock",
"# These defines determine how often the appmock server will be requested #",
"def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of messages exactly matching given message,",
"raise Exception( 'tcp_server_specific_message_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port,",
"/ 1000.0) # No incrementing wait time here because # this fun might",
"error: ' + body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request",
"tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of connections are",
"of connections are established on given port, or after it timeouts. The accept_more",
"been received by the TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _,",
"history connected with ALL mocked TCP endpoints. The reset will cause this instance",
"self.ip = client.ip self.port = port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary)",
"result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result >= msg_count: break elif",
"endpoint_port, endpoint_path): \"\"\" Returns how many times has given endpoint been requested. IMPORTANT:",
"function to return full msg history upon success. \"\"\" start_time = time.time() wait_for",
"'tcp_server_specific_message_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1,",
"error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip,",
"wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result",
"+ body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints were",
"makes the function succeed when there is the same or more connections than",
"\"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '')",
"message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self):",
"def reset_rest_history(appmock_ip): \"\"\" Performs a request to an appmock instance to reset all",
"return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of messages exactly matching",
"error: ' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\"",
"self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port,",
"True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned",
"appmock to send given message to all connected clients, given amount of times.",
"to an appmock instance to obtain full history of messages received on given",
"def history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary,",
"port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port)",
"many clients are connected to given endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port)",
"appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body) if body['result'] == 'error': raise Exception(",
"def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client = client",
"== 'error': raise Exception( 'tcp_server_specific_message_count returned error: ' + body['reason']) return body['result'] def",
"def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all messages that has been received",
"request to an appmock instance to reset all the history connected with ALL",
"Authors: <NAME> Copyright (C) 2015 ACK CYFRONET AGH This software is released under",
"cause this instance to act the same as if it was restarted clean.",
"this instance to act the same as if it was restarted clean. \"\"\"",
"True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error:",
"history does not match: ' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs",
"verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how",
"encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned error:",
"'error': raise Exception( 'reset_tcp_history returned error: ' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip,",
"timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port, path,",
"for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs",
"= base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port, path,",
"history connected with ALL mocked rest endpoints. The reset will cause this instance",
"same or more messages than expected. The return_history flag causes the function to",
"wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary,",
"return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to",
"tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return",
"example: '/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port, 'path': endpoint_path } _, _,",
"<NAME> Copyright (C) 2015 ACK CYFRONET AGH This software is released under the",
"as if it was restarted clean. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"timeouts. The accept_more flag makes the function succeed when there is the same",
"tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all messages that has been received by",
"body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints were requested",
"return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance",
"tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >= msg_count: break elif result == msg_count:",
"return elif result == number_of_connections: return elif time.time() - start_time > timeout_sec: raise",
"client self.ip = client.ip self.port = port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port,",
"raise Exception( 'tcp_server_connection_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port,",
"return_history, timeout_sec) def _http_post(ip, port, path, use_ssl, data): \"\"\" Helper function that perform",
"break elif result == msg_count: break elif time.time() - start_time > timeout_sec: raise",
"= client.ip self.port = port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def",
"time here because # this fun might be used for benchmarking. if return_history:",
"many times has given endpoint been requested. IMPORTANT: the endpoint_path must be literally",
"Body) \"\"\" protocol = 'https' if use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol,",
"No incrementing wait time here because # this fun might be used for",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'reset_rest_history returned error: ' +",
"tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to send given message to all",
"time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and",
"Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if",
"wait time here because # this fun might be used for benchmarking. if",
"\"\"\" json_data = { 'port': endpoint_port, 'path': endpoint_path } _, _, body =",
"True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception( 'expected history",
"= client self.ip = client.ip self.port = port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip,",
"accept_more and result >= msg_count: break elif result == msg_count: break elif time.time()",
"history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count)",
"Exception( 'tcp_server_specific_message_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary,",
"} return entry json_data = [create_endpoint_entry(port, path) for (port, path) in expected_history] _,",
"to act the same as if it was restarted clean - e. g.",
"_http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise",
"check for condition when waiting for something. # Increment rate causes each next",
"tcp_port): \"\"\" Performs a request to an appmock instance to check how many",
"import json import time import requests # Appmock remote control port appmock_rc_port =",
"# to check for condition when waiting for something. # Increment rate causes",
"message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return",
"for example: '/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port, 'path': endpoint_path } _,",
"tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port, path, use_ssl, data):",
"cited in 'LICENSE.txt' Client library to contact appmock instances. \"\"\" import base64 import",
"expected. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip,",
"Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) # No incrementing wait",
"\"\"\" import base64 import json import time import requests # Appmock remote control",
"\"\"\" Returns number of all messages that has been received by the TCP",
"accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False,",
"returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False,",
"_http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body) if body['result'] == 'error': raise",
"tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all messages that has been",
"def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints were requested in given order.",
"return_history flag causes the function to return full msg history upon success. \"\"\"",
"if body['result'] == 'error': raise Exception( 'expected history does not match: ' +",
"of messages exactly matching given message, that has been received by the TCP",
"body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of messages exactly",
"= port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip,",
"body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request to an appmock instance to reset",
"Exception( 'reset_tcp_history returned error: ' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\"",
"ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self):",
"return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an appmock instance to",
"if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body) if",
"might be used for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port,",
"if body['result'] == 'error': raise Exception( 'reset_tcp_history returned error: ' + body['reason']) return",
"\"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"path, True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count",
"(8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry = { 'endpoint': { 'path': _path,",
"_http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body) if body['result'] == 'error': raise",
"body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error: ' +",
"json_data = { 'port': endpoint_port, 'path': endpoint_path } _, _, body = _http_post(appmock_ip,",
"The reset will cause this instance to act the same as if it",
"= _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error':",
"\"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body)",
"when there is the same or more connections than expected. \"\"\" start_time =",
"in given order. Returns True or False. The expected_history is a list of",
"raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) # No incrementing",
"'path': _path, 'port': _port } } return entry json_data = [create_endpoint_entry(port, path) for",
"[(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry = { 'endpoint': {",
"received by the TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body",
"'tcp_server_all_messages_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False,",
"time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for",
"succeed when there is the same or more messages than expected. The return_history",
"not match: ' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request",
"any messages has been received on given port, or after it timeouts. The",
"True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_tcp_history returned",
"} } return entry json_data = [create_endpoint_entry(port, path) for (port, path) in expected_history]",
"'/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port, 'path': endpoint_path } _, _, body",
"self.port) def history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port,",
"has given endpoint been requested. IMPORTANT: the endpoint_path must be literally the same",
"was restarted clean. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '')",
"msg history upon success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True:",
"rate causes each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE =",
"reset. Existing connections WILL NOT BE DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip,",
"+ body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when",
"(Code, Headers, Body) \"\"\" protocol = 'https' if use_ssl else 'http' response =",
"BE DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body",
"software is released under the MIT license cited in 'LICENSE.txt' Client library to",
"accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary,",
"reset all the history connected with ALL mocked TCP endpoints. The reset will",
"that perform a HTTP GET request Returns a tuple (Code, Headers, Body) \"\"\"",
"'') body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_rest_history returned error:",
"instances. \"\"\" import base64 import json import time import requests # Appmock remote",
"WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip",
"json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) for",
"timeout_sec) def _http_post(ip, port, path, use_ssl, data): \"\"\" Helper function that perform a",
"reset all the history connected with ALL mocked rest endpoints. The reset will",
"accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1,",
"error: ' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number",
"or more messages than expected. The return_history flag causes the function to return",
"\"\"\" Orders appmock to send given message to all connected clients, given amount",
"body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given",
"cause this instance to act the same as if it was restarted clean",
"number of connections are established on given port, or after it timeouts. The",
"is the same or more messages than expected. The return_history flag causes the",
"port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True,",
"response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many times has given endpoint",
"_, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if body['result']",
"self.client = client self.ip = client.ip self.port = port def specific_message_count(self, message_binary): return",
"\"\"\" Helper function that perform a HTTP GET request Returns a tuple (Code,",
"match: ' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request to",
"WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >= number_of_connections:",
"accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of connections are established on given",
"reset will cause this instance to act the same as if it was",
"- start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for /",
"break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout')",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned error: ' +",
"IMPORTANT: the endpoint_path must be literally the same as in app_desc module, for",
"return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip,",
"appmock instance to reset all the history connected with ALL mocked rest endpoints.",
"The accept_more flag makes the function succeed when there is the same or",
"all connected clients, given amount of times. \"\"\" encoded_message = base64.b64encode(message_binary) path =",
"messages received on given endpoint. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port),",
"raise Exception( 'tcp_server_connection_count returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE",
"'error': raise Exception( 'reset_rest_history returned error: ' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip,",
"accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip,",
"body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an appmock instance to reset",
"'error': raise Exception( 'rest_endpoint_request_count returned error: ' + body['reason']) return body['result'] def verify_rest_history(appmock_ip,",
"result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >= number_of_connections: return elif result",
"accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of specific messages has been",
"WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >= msg_count:",
"Exception( 'expected history does not match: ' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip):",
"been received on given port, or after it timeouts. The accept_more flag makes",
"when waiting for something. # Increment rate causes each next interval to be",
"given port, or after it timeouts. The accept_more flag makes the function succeed",
"full msg history upon success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while",
"'https' if use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data,",
"body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body) if body['result'] ==",
"body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) return body['result'] def",
"succeed when there is the same or more connections than expected. \"\"\" start_time",
"number of messages exactly matching given message, that has been received by the",
"that has been received by the TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port)",
"of all messages that has been received by the TCP server mock. \"\"\"",
"CYFRONET AGH This software is released under the MIT license cited in 'LICENSE.txt'",
"specific messages has been received on given port, or after it timeouts. The",
"msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of any messages has",
"accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of any messages has been",
"start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for / 1000.0)",
"Exception('tcp_server_send returned error: ' + body['reason']) return body['result'] def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs",
"timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def",
"start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if",
"_http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body) if body['result'] == 'error': raise",
"'LICENSE.txt' Client library to contact appmock instances. \"\"\" import base64 import json import",
"for something. # Increment rate causes each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL",
"message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more,",
"Returns a tuple (Code, Headers, Body) \"\"\" protocol = 'https' if use_ssl else",
"def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more,",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'reset_tcp_history returned error: ' +",
"in 'LICENSE.txt' Client library to contact appmock instances. \"\"\" import base64 import json",
"\"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '')",
"endpoints were requested in given order. Returns True or False. The expected_history is",
"== 'error': raise Exception( 'rest_endpoint_request_count returned error: ' + body['reason']) return body['result'] def",
"tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self,",
"data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns",
"self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port, path, use_ssl, data): \"\"\"",
"'error': raise Exception( 'tcp_server_connection_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip,",
"connected with ALL mocked rest endpoints. The reset will cause this instance to",
"start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if",
"def _http_post(ip, port, path, use_ssl, data): \"\"\" Helper function that perform a HTTP",
"requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def",
"Returns how many times has given endpoint been requested. IMPORTANT: the endpoint_path must",
"def create_endpoint_entry(_port, _path): entry = { 'endpoint': { 'path': _path, 'port': _port }",
"== 'error': raise Exception( 'tcp_server_all_messages_count returned error: ' + body['reason']) return body['result'] def",
"tcp_port, message_binary): \"\"\" Returns number of messages exactly matching given message, that has",
"'') body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned error:",
"WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result >=",
"# coding=utf-8 \"\"\" Authors: <NAME> Copyright (C) 2015 ACK CYFRONET AGH This software",
"msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history,",
"The return_history flag causes the function to return full msg history upon success.",
"result == msg_count: break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages",
"base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True,",
"return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port)",
"be literally the same as in app_desc module, for example: '/test1/[:binding]' \"\"\" json_data",
"if body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) return body['result']",
"appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body) if body['result'] == 'error': raise Exception(",
"+ body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\"",
"'') body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_tcp_history returned error:",
"Existing connections WILL NOT BE DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >= msg_count: break",
"given endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip,",
"= 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip =",
"def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self,",
"'/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body =",
"expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body)",
"'/reset_tcp_server_history', True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_tcp_history",
"that has been received by the TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary)",
"response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers,",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_tcp_history returned error: '",
"will be requested # to check for condition when waiting for something. #",
"flag makes the function succeed when there is the same or more connections",
"number of all messages that has been received by the TCP server mock.",
"def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance to check",
"endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned error: ' + body['reason']) return",
"\"\"\" Returns when given number of specific messages has been received on given",
"same as in app_desc module, for example: '/test1/[:binding]' \"\"\" json_data = { 'port':",
"== 'error': raise Exception( 'tcp_server_connection_count returned error: ' + body['reason']) return body['result'] def",
"\"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body)",
"given order. Returns True or False. The expected_history is a list of tuples",
"raise Exception( 'tcp_server_all_messages_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port,",
"endpoints. The reset will cause this instance to act the same as if",
"been requested. IMPORTANT: the endpoint_path must be literally the same as in app_desc",
"def tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance to obtain",
"def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return",
"order. Returns True or False. The expected_history is a list of tuples (port,",
"\"\"\" Returns when given number of any messages has been received on given",
"appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception(",
"path, True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count",
"return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all messages",
"json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned error: ' + body['reason'])",
"port, path, use_ssl, data): \"\"\" Helper function that perform a HTTP GET request",
"response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many times has",
"TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body",
"def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def",
"msg_count: break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error:",
"DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip = ip def",
"Helper function that perform a HTTP GET request Returns a tuple (Code, Headers,",
"_, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if body['result']",
"return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client = client self.ip =",
"port, or after it timeouts. The accept_more flag makes the function succeed when",
"= _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error':",
"client, port): self.client = client self.ip = client.ip self.port = port def specific_message_count(self,",
"protocol = 'https' if use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port,",
"body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned error: ' + body['reason']) return body['result']",
"appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception(",
"body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned error: ' + body['reason']) return body['result']",
"reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client =",
"/ 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port):",
"return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False,",
"str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request to an appmock instance",
"flag makes the function succeed when there is the same or more messages",
"reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port):",
"result >= number_of_connections: return elif result == number_of_connections: return elif time.time() - start_time",
"msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def",
"_http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise",
"' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of",
"matching given message, that has been received by the TCP server mock. \"\"\"",
"# Appmock remote control port appmock_rc_port = 9999 # These defines determine how",
"expected_history is a list of tuples (port, path), for example: [(8080, '/test1/[:binding]'), (8080,",
"_, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body) if body['result']",
"ALL mocked rest endpoints. The reset will cause this instance to act the",
"returned error: ' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns",
"requests # Appmock remote control port appmock_rc_port = 9999 # These defines determine",
"body['result'] == 'error': raise Exception( 'expected history does not match: ' + str(body['history']))",
"base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message)",
"this fun might be used for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def",
"range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to",
"appmock instance to check how many clients are connected to given endpoint (by",
"a HTTP GET request Returns a tuple (Code, Headers, Body) \"\"\" protocol =",
"will cause this instance to act the same as if it was restarted",
"return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all messages that",
"incrementing wait time here because # this fun might be used for benchmarking.",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned error: ' +",
"elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else:",
"timeout') else: time.sleep(wait_for / 1000.0) # No incrementing wait time here because #",
"mock. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip,",
"same or more connections than expected. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL",
"tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >= number_of_connections: return elif result == number_of_connections:",
"use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT)",
"use_ssl, data): \"\"\" Helper function that perform a HTTP GET request Returns a",
"*= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number",
"all the history connected with ALL mocked TCP endpoints. The reset will cause",
"a request to an appmock instance to check how many clients are connected",
"be reset. Existing connections WILL NOT BE DISTURBED. \"\"\" _, _, body =",
"def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary,",
"with ALL mocked rest endpoints. The reset will cause this instance to act",
"result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >= msg_count: break elif result",
"' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to",
"= 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip = ip def tcp_endpoint(self,",
"error: timeout') else: time.sleep(wait_for / 1000.0) # No incrementing wait time here because",
"time import requests # Appmock remote control port appmock_rc_port = 9999 # These",
"start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for / 1000.0)",
"= _http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body) if body['result'] == 'error':",
"= _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if body['result'] == 'error':",
"number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of connections are established on",
">= msg_count: break elif result == msg_count: break elif time.time() - start_time >",
"else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def",
"Headers, Body) \"\"\" protocol = 'https' if use_ssl else 'http' response = requests.post(",
"'/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count",
"WILL NOT BE DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True,",
"wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result",
"\"\"\" Authors: <NAME> Copyright (C) 2015 ACK CYFRONET AGH This software is released",
"json.loads(body) if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned error: ' + body['reason'])",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned error: '",
"clients, given amount of times. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count)",
"instance to reset all the history connected with ALL mocked TCP endpoints. The",
"the history connected with ALL mocked rest endpoints. The reset will cause this",
"> timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for",
"fun might be used for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip,",
"message_binary, msg_count=1): return tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT):",
"return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return",
"tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port) def",
"reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an appmock instance to reset all the",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned error: '",
"ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port,",
"port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self,",
"== number_of_connections: return elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned",
"body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body) if body['result'] ==",
"returned error: ' + body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if",
"timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) # No",
"True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >= number_of_connections: return elif",
"an appmock instance to reset all the history connected with ALL mocked rest",
"the same or more connections than expected. \"\"\" start_time = time.time() wait_for =",
"to act the same as if it was restarted clean. \"\"\" _, _,",
"body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance to",
"result == msg_count: break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages",
"= _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body) if body['result'] == 'error':",
"the MIT license cited in 'LICENSE.txt' Client library to contact appmock instances. \"\"\"",
"by the TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body =",
"entry = { 'endpoint': { 'path': _path, 'port': _port } } return entry",
"a request to an appmock instance to obtain full history of messages received",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_rest_history returned error: '",
"path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message)",
"has been received on given port, or after it timeouts. The accept_more flag",
"tcp_server_connection_count(self.ip, self.port) def history(self): return tcp_server_history(self.ip, self.port) def send(self, message_binary, msg_count=1): return tcp_server_send(self.ip,",
"to all connected clients, given amount of times. \"\"\" encoded_message = base64.b64encode(message_binary) path",
"mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True,",
"'/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body)",
"and result >= msg_count: break elif result == msg_count: break elif time.time() -",
"elif result == msg_count: break elif time.time() - start_time > timeout_sec: raise Exception(",
"be requested # to check for condition when waiting for something. # Increment",
"= json.loads(body) if body['result'] == 'error': raise Exception( 'expected history does not match:",
"if it was restarted clean - e. g. counters will be reset. Existing",
"app_desc module, for example: '/test1/[:binding]' \"\"\" json_data = { 'port': endpoint_port, 'path': endpoint_path",
"server will be requested # to check for condition when waiting for something.",
"endpoint_path): \"\"\" Returns how many times has given endpoint been requested. IMPORTANT: the",
"tuples (port, path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path):",
"coding=utf-8 \"\"\" Authors: <NAME> Copyright (C) 2015 ACK CYFRONET AGH This software is",
"import base64 import json import time import requests # Appmock remote control port",
"ALL mocked TCP endpoints. The reset will cause this instance to act the",
"clients are connected to given endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _,",
"json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned error: ' + body['reason'])",
"tcp_port, message_binary) if accept_more and result >= msg_count: break elif result == msg_count:",
"path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body",
"perform a HTTP GET request Returns a tuple (Code, Headers, Body) \"\"\" protocol",
"json.loads(body) if body['result'] == 'error': raise Exception( 'expected history does not match: '",
"library to contact appmock instances. \"\"\" import base64 import json import time import",
"time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_connection_count returned error: timeout') else: time.sleep(wait_for",
"to obtain full history of messages received on given endpoint. \"\"\" _, _,",
"number_of_connections: return elif result == number_of_connections: return elif time.time() - start_time > timeout_sec:",
"message_binary, msg_count=1): \"\"\" Orders appmock to send given message to all connected clients,",
"{ 'endpoint': { 'path': _path, 'port': _port } } return entry json_data =",
"is released under the MIT license cited in 'LICENSE.txt' Client library to contact",
"on given port, or after it timeouts. The accept_more flag makes the function",
"Exception('tcp_server_send returned error: ' + body['reason']) for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i])",
"= [create_endpoint_entry(port, path) for (port, path) in expected_history] _, _, body = _http_post(appmock_ip,",
"longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60 requests.packages.urllib3.disable_warnings() class AppmockClient(object):",
"> timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body = json.loads(body) if",
"waiting for something. # Increment rate causes each next interval to be longer.",
"'/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if body['result'] == 'error': raise Exception( 'expected",
"are connected to given endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _,",
"= time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more",
"appmock instances. \"\"\" import base64 import json import time import requests # Appmock",
"must be literally the same as in app_desc module, for example: '/test1/[:binding]' \"\"\"",
"port): self.client = client self.ip = client.ip self.port = port def specific_message_count(self, message_binary):",
"path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body",
"wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns",
"request to an appmock instance to obtain full history of messages received on",
"return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to send",
"base64 import json import time import requests # Appmock remote control port appmock_rc_port",
"act the same as if it was restarted clean. \"\"\" _, _, body",
"to contact appmock instances. \"\"\" import base64 import json import time import requests",
"+ str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request to an appmock",
"body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an",
"endpoint_path must be literally the same as in app_desc module, for example: '/test1/[:binding]'",
"__init__(self, client, port): self.client = client self.ip = client.ip self.port = port def",
"return entry json_data = [create_endpoint_entry(port, path) for (port, path) in expected_history] _, _,",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body) if",
"verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints were requested in given order. Returns",
"on given endpoint. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '')",
"Orders appmock to send given message to all connected clients, given amount of",
"while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >= number_of_connections: return",
"as if it was restarted clean - e. g. counters will be reset.",
"body['result'] == 'error': raise Exception( 'reset_rest_history returned error: ' + body['reason']) return body['result']",
"the function succeed when there is the same or more connections than expected.",
"<reponame>kzemek/helpers<filename>appmock/appmock_client.py # coding=utf-8 \"\"\" Authors: <NAME> Copyright (C) 2015 ACK CYFRONET AGH This",
"Increment rate causes each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE",
"full history of messages received on given endpoint. \"\"\" _, _, body =",
"function that perform a HTTP GET request Returns a tuple (Code, Headers, Body)",
"_path): entry = { 'endpoint': { 'path': _path, 'port': _port } } return",
"'/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry = { 'endpoint': { 'path': _path, 'port':",
"self.port, number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip,",
"clean. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body =",
"in expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body =",
"connected with ALL mocked TCP endpoints. The reset will cause this instance to",
"elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else:",
"to check how many clients are connected to given endpoint (by port). \"\"\"",
"received on given endpoint. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True,",
"returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return",
"'/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned",
"if use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False,",
"' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\"",
"== msg_count: break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned",
"json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned error: ' + body['reason'])",
"if accept_more and result >= number_of_connections: return elif result == number_of_connections: return elif",
"error: ' + body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest",
"msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of specific messages has",
"1000.0) # No incrementing wait time here because # this fun might be",
"requested in given order. Returns True or False. The expected_history is a list",
"# this fun might be used for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port)",
"was restarted clean - e. g. counters will be reset. Existing connections WILL",
"rest endpoints. The reset will cause this instance to act the same as",
"return full msg history upon success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL",
"Exception( 'tcp_server_all_messages_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1,",
"= ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def",
"def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of",
"msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body)",
"number of specific messages has been received on given port, or after it",
"= WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result",
"'/tcp_server_all_messages_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body)",
"rest endpoints were requested in given order. Returns True or False. The expected_history",
"time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for",
"[create_endpoint_entry(port, path) for (port, path) in expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"given number of connections are established on given port, or after it timeouts.",
"body = _http_post(appmock_ip, appmock_rc_port, path, True, encoded_message) body = json.loads(body) if body['result'] ==",
"the same or more messages than expected. The return_history flag causes the function",
"\"\"\" def create_endpoint_entry(_port, _path): entry = { 'endpoint': { 'path': _path, 'port': _port",
"wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and",
"accept_more and result >= number_of_connections: return elif result == number_of_connections: return elif time.time()",
"body['result'] == 'error': raise Exception( 'reset_tcp_history returned error: ' + body['reason']) return body['result']",
"appmock_rc_port = 9999 # These defines determine how often the appmock server will",
"return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of any messages has been received",
"the endpoint_path must be literally the same as in app_desc module, for example:",
"will be reset. Existing connections WILL NOT BE DISTURBED. \"\"\" _, _, body",
"tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of any",
"(port, path) in expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data))",
"= 'https' if use_ssl else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path),",
"These defines determine how often the appmock server will be requested # to",
"list of tuples (port, path), for example: [(8080, '/test1/[:binding]'), (8080, '/test2')] \"\"\" def",
"if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of all",
"used for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1):",
"= WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >=",
"body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body = json.loads(body) if body['result'] ==",
"self.ip = ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip)",
"True or False. The expected_history is a list of tuples (port, path), for",
"tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip,",
"return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return",
"accept_more, return_history, timeout_sec) def wait_for_connections(self, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_connections(self.ip, self.port, number_of_connections, accept_more,",
"causes the function to return full msg history upon success. \"\"\" start_time =",
"received by the TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port)",
"success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip,",
"body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) for i in",
"else 'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return",
"tcp_server_send(self.ip, self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port,",
"to an appmock instance to reset all the history connected with ALL mocked",
"messages exactly matching given message, that has been received by the TCP server",
"appmock_rc_port, path, True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send",
"return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client",
"\"\"\" Performs a request to an appmock instance to reset all the history",
"of messages received on given endpoint. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"def reset_tcp_server_history(appmock_ip): \"\"\" Performs a request to an appmock instance to reset all",
"same as if it was restarted clean - e. g. counters will be",
"\"\"\" Verifies if rest endpoints were requested in given order. Returns True or",
"- start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for /",
"' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a request to an",
"Copyright (C) 2015 ACK CYFRONET AGH This software is released under the MIT",
"body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_specific_message_count returned error: '",
"timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *=",
"break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error: timeout')",
"if body['result'] == 'error': raise Exception( 'tcp_server_connection_count returned error: ' + body['reason']) return",
"endpoint_port, 'path': endpoint_path } _, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data))",
"a request to an appmock instance to reset all the history connected with",
"than expected. The return_history flag causes the function to return full msg history",
"here because # this fun might be used for benchmarking. if return_history: return",
"clean - e. g. counters will be reset. Existing connections WILL NOT BE",
"while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result >= msg_count:",
"returned error: ' + body['reason']) for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return",
"Exception( 'reset_rest_history returned error: ' + body['reason']) return body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary):",
"if body['result'] == 'error': raise Exception( 'reset_rest_history returned error: ' + body['reason']) return",
"tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of messages exactly matching given message, that",
"an appmock instance to reset all the history connected with ALL mocked TCP",
"error: ' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False,",
"connections are established on given port, or after it timeouts. The accept_more flag",
"Exception( 'rest_endpoint_request_count returned error: ' + body['reason']) return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\"",
"return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port,",
"defines determine how often the appmock server will be requested # to check",
"AGH This software is released under the MIT license cited in 'LICENSE.txt' Client",
"causes each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3",
"when given number of specific messages has been received on given port, or",
"port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path):",
"function succeed when there is the same or more connections than expected. \"\"\"",
"'reset_tcp_history returned error: ' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs",
"else: time.sleep(wait_for / 1000.0) # No incrementing wait time here because # this",
"encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _, _, body = _http_post(appmock_ip, appmock_rc_port,",
"the function succeed when there is the same or more messages than expected.",
"received on given port, or after it timeouts. The accept_more flag makes the",
"the TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _,",
"does not match: ' + str(body['history'])) return body['result'] def reset_rest_history(appmock_ip): \"\"\" Performs a",
"encoded_message = base64.b64encode(message_binary) path = '/tcp_server_specific_message_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path,",
"control port appmock_rc_port = 9999 # These defines determine how often the appmock",
"AppmockClient(object): def __init__(self, ip): self.ip = ip def tcp_endpoint(self, port): return AppmockTCPEndpoint(self, port)",
"an appmock instance to obtain full history of messages received on given endpoint.",
"_, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body) if body['result']",
"appmock_rc_port, path, True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception(",
"are established on given port, or after it timeouts. The accept_more flag makes",
"GET request Returns a tuple (Code, Headers, Body) \"\"\" protocol = 'https' if",
"message to all connected clients, given amount of times. \"\"\" encoded_message = base64.b64encode(message_binary)",
"returned error: ' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a",
"'tcp_server_wait_for_specific_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history:",
"HTTP GET request Returns a tuple (Code, Headers, Body) \"\"\" protocol = 'https'",
"act the same as if it was restarted clean - e. g. counters",
"released under the MIT license cited in 'LICENSE.txt' Client library to contact appmock",
"the same as if it was restarted clean - e. g. counters will",
"import requests # Appmock remote control port appmock_rc_port = 9999 # These defines",
"True: result = tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result >= msg_count: break",
"result >= msg_count: break elif result == msg_count: break elif time.time() - start_time",
"determine how often the appmock server will be requested # to check for",
"for benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\"",
"path, True, encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned",
"message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of specific messages",
"AppmockTCPEndpoint(self, port) def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body = json.loads(body) if",
"number_of_connections, accept_more, timeout_sec) def wait_for_specific_messages(self, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port,",
"body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number of",
"been received by the TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path =",
"messages has been received on given port, or after it timeouts. The accept_more",
"tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result >= msg_count: break elif result ==",
"return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given number",
"WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_all_messages_count(appmock_ip, tcp_port): \"\"\" Returns number of",
"\"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip, tcp_port,",
"body['reason']) return body['result'] def tcp_server_wait_for_connections(appmock_ip, tcp_port, number_of_connections=1, accept_more=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when given",
"more messages than expected. The return_history flag causes the function to return full",
"requested # to check for condition when waiting for something. # Increment rate",
"# No incrementing wait time here because # this fun might be used",
"AppmockTCPEndpoint(object): def __init__(self, client, port): self.client = client self.ip = client.ip self.port =",
"+ body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to an",
"endpoint been requested. IMPORTANT: the endpoint_path must be literally the same as in",
"== 'error': raise Exception( 'reset_rest_history returned error: ' + body['reason']) return body['result'] def",
"body['result'] == 'error': raise Exception( 'tcp_server_all_messages_count returned error: ' + body['reason']) return body['result']",
"+ body['reason']) return body['result'] def tcp_server_wait_for_any_messages(appmock_ip, tcp_port, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns",
"'error': raise Exception( 'tcp_server_specific_message_count returned error: ' + body['reason']) return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip,",
"class AppmockTCPEndpoint(object): def __init__(self, client, port): self.client = client self.ip = client.ip self.port",
"msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count, accept_more, return_history, timeout_sec) def wait_for_connections(self,",
"of specific messages has been received on given port, or after it timeouts.",
"'/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body)",
"\"\"\" Performs a request to an appmock instance to obtain full history of",
"when given number of any messages has been received on given port, or",
"tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self): return tcp_server_connection_count(self.ip, self.port)",
"success. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_specific_message_count(appmock_ip,",
"to given endpoint (by port). \"\"\" path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body =",
"9999 # These defines determine how often the appmock server will be requested",
"'tcp_server_wait_for_any_messages returned error: timeout') else: time.sleep(wait_for / 1000.0) # No incrementing wait time",
"' + body['reason']) for i in range(len(body['result'])): body['result'][i] = base64.b64decode(body['result'][i]) return body['result'] def",
"return body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints were requested in",
"= _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body) if body['result'] == 'error':",
"Verifies if rest endpoints were requested in given order. Returns True or False.",
"given amount of times. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port, msg_count) _,",
"path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\"",
"def rest_endpoint_request_count(appmock_ip, endpoint_port, endpoint_path): \"\"\" Returns how many times has given endpoint been",
"entry json_data = [create_endpoint_entry(port, path) for (port, path) in expected_history] _, _, body",
"= tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary) if accept_more and result >= msg_count: break elif result",
"timeout') else: time.sleep(wait_for / 1000.0) wait_for *= WAIT_INTERVAL_INCREMENT_RATE if return_history: return tcp_server_history(appmock_ip, tcp_port)",
"_, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body = json.loads(body) if body['result']",
"history of messages received on given endpoint. \"\"\" _, _, body = _http_post(appmock_ip,",
"connected clients, given amount of times. \"\"\" encoded_message = base64.b64encode(message_binary) path = '/tcp_server_send/{0}/{1}'.format(tcp_port,",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, '/tcp_server_history/{0}'.format(tcp_port), True, '') body = json.loads(body) if",
"if body['result'] == 'error': raise Exception('tcp_server_send returned error: ' + body['reason']) for i",
"check how many clients are connected to given endpoint (by port). \"\"\" path",
"path, True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'tcp_server_connection_count",
"interval to be longer. WAIT_STARTING_CHECK_INTERVAL = 250 WAIT_INTERVAL_INCREMENT_RATE = 1.3 DEFAULT_TIMEOUT = 60",
"'/reset_rest_history', True, '') body = json.loads(body) if body['result'] == 'error': raise Exception( 'reset_rest_history",
"tcp_server_history(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance to obtain full",
"tcp_port) if accept_more and result >= msg_count: break elif result == msg_count: break",
"= '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body =",
"'/test1/[:binding]'), (8080, '/test2')] \"\"\" def create_endpoint_entry(_port, _path): entry = { 'endpoint': { 'path':",
"same as if it was restarted clean. \"\"\" _, _, body = _http_post(appmock_ip,",
"True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >= msg_count: break elif",
"endpoint_path } _, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count', True, json.dumps(json_data)) body =",
"mocked TCP endpoints. The reset will cause this instance to act the same",
"to reset all the history connected with ALL mocked rest endpoints. The reset",
"if body['result'] == 'error': raise Exception( 'rest_endpoint_request_count returned error: ' + body['reason']) return",
"Performs a request to an appmock instance to reset all the history connected",
"tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock instance to check how",
"60 requests.packages.urllib3.disable_warnings() class AppmockClient(object): def __init__(self, ip): self.ip = ip def tcp_endpoint(self, port):",
"after it timeouts. The accept_more flag makes the function succeed when there is",
"Performs a request to an appmock instance to check how many clients are",
"_, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history', True, '') body = json.loads(body) if",
"= WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_all_messages_count(appmock_ip, tcp_port) if accept_more and result >=",
"to check for condition when waiting for something. # Increment rate causes each",
"body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port): \"\"\" Performs a request to an appmock",
"it was restarted clean - e. g. counters will be reset. Existing connections",
"if it was restarted clean. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_rest_history',",
"message_binary, msg_count, accept_more, return_history, timeout_sec) def _http_post(ip, port, path, use_ssl, data): \"\"\" Helper",
"the same as in app_desc module, for example: '/test1/[:binding]' \"\"\" json_data = {",
"client.ip self.port = port def specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self):",
"given message to all connected clients, given amount of times. \"\"\" encoded_message =",
"'http' response = requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code,",
"tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to send given message",
"def reset_rest_history(self): return reset_rest_history(self.ip) def reset_tcp_history(self): return reset_tcp_server_history(self.ip) class AppmockTCPEndpoint(object): def __init__(self, client,",
"{ 'port': endpoint_port, 'path': endpoint_path } _, _, body = _http_post(appmock_ip, appmock_rc_port, '/rest_endpoint_request_count',",
"benchmarking. if return_history: return tcp_server_history(appmock_ip, tcp_port) def tcp_server_send(appmock_ip, tcp_port, message_binary, msg_count=1): \"\"\" Orders",
"returned error: timeout') else: time.sleep(wait_for / 1000.0) # No incrementing wait time here",
"self.port, message_binary, msg_count) def wait_for_any_messages(self, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_any_messages(self.ip, self.port, msg_count,",
"'error': raise Exception('tcp_server_send returned error: ' + body['reason']) for i in range(len(body['result'])): body['result'][i]",
"path = '/tcp_server_connection_count/{0}'.format(tcp_port) _, _, body = _http_post(appmock_ip, appmock_rc_port, path, True, '') body",
"given endpoint been requested. IMPORTANT: the endpoint_path must be literally the same as",
"body['result'] def verify_rest_history(appmock_ip, expected_history): \"\"\" Verifies if rest endpoints were requested in given",
"create_endpoint_entry(_port, _path): entry = { 'endpoint': { 'path': _path, 'port': _port } }",
"message_binary): \"\"\" Returns number of messages exactly matching given message, that has been",
"has been received by the TCP server mock. \"\"\" path = '/tcp_server_all_messages_count/{0}'.format(tcp_port) _,",
"appmock instance to reset all the history connected with ALL mocked TCP endpoints.",
"path) in expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history', True, json.dumps(json_data)) body",
"\"\"\" Performs a request to an appmock instance to check how many clients",
"tcp_port): \"\"\" Performs a request to an appmock instance to obtain full history",
"= { 'endpoint': { 'path': _path, 'port': _port } } return entry json_data",
"message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): return tcp_server_wait_for_specific_messages(self.ip, self.port, message_binary, msg_count, accept_more, return_history, timeout_sec)",
"body['result'] def tcp_server_specific_message_count(appmock_ip, tcp_port, message_binary): \"\"\" Returns number of messages exactly matching given",
"has been received by the TCP server mock. \"\"\" encoded_message = base64.b64encode(message_binary) path",
"specific_message_count(self, message_binary): return tcp_server_specific_message_count(self.ip, self.port, message_binary) def all_messages_count(self): return tcp_server_all_messages_count(self.ip, self.port) def connection_count(self):",
"msg_count=1): \"\"\" Orders appmock to send given message to all connected clients, given",
"there is the same or more connections than expected. \"\"\" start_time = time.time()",
"json import time import requests # Appmock remote control port appmock_rc_port = 9999",
"return body['result'] def tcp_server_wait_for_specific_messages(appmock_ip, tcp_port, message_binary, msg_count=1, accept_more=False, return_history=False, timeout_sec=DEFAULT_TIMEOUT): \"\"\" Returns when",
"\"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result = tcp_server_connection_count(appmock_ip, tcp_port)",
"than expected. \"\"\" start_time = time.time() wait_for = WAIT_STARTING_CHECK_INTERVAL while True: result =",
"msg_count: break elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_wait_for_specific_messages returned error:",
"raise Exception( 'reset_tcp_history returned error: ' + body['reason']) return body['result'] def tcp_server_connection_count(appmock_ip, tcp_port):",
"tcp_port, message_binary, msg_count=1): \"\"\" Orders appmock to send given message to all connected",
"encoded_message) body = json.loads(body) if body['result'] == 'error': raise Exception('tcp_server_send returned error: '",
"result == number_of_connections: return elif time.time() - start_time > timeout_sec: raise Exception( 'tcp_server_connection_count",
"Performs a request to an appmock instance to obtain full history of messages",
"literally the same as in app_desc module, for example: '/test1/[:binding]' \"\"\" json_data =",
"appmock_rc_port, path, True, '') body = json.loads(body) if body['result'] == 'error': raise Exception(",
"Returns when given number of any messages has been received on given port,",
"something. # Increment rate causes each next interval to be longer. WAIT_STARTING_CHECK_INTERVAL =",
"restarted clean - e. g. counters will be reset. Existing connections WILL NOT",
"this instance to act the same as if it was restarted clean -",
"DISTURBED. \"\"\" _, _, body = _http_post(appmock_ip, appmock_rc_port, '/reset_tcp_server_history', True, '') body =",
"instance to act the same as if it was restarted clean - e.",
"or False. The expected_history is a list of tuples (port, path), for example:",
"often the appmock server will be requested # to check for condition when",
"all messages that has been received by the TCP server mock. \"\"\" path",
"= tcp_server_connection_count(appmock_ip, tcp_port) if accept_more and result >= number_of_connections: return elif result ==",
"= requests.post( '{0}://{1}:{2}{3}'.format(protocol, ip, port, path), data, verify=False, timeout=DEFAULT_TIMEOUT) return response.status_code, response.headers, response.text",
"path) for (port, path) in expected_history] _, _, body = _http_post(appmock_ip, appmock_rc_port, '/verify_rest_history',",
"and result >= number_of_connections: return elif result == number_of_connections: return elif time.time() -"
] |
[
"record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0)) print(utils.get_name(record['nombre'], 1)) print(utils.get_name(record['nombre'], 2)) print(utils.get_name(record['nombre'], 3))",
"<filename>test/DATA_FLOW/Descriptor/utils_test.py import DataFlow.Descriptor.utils as utils record = { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\":",
"utils record = { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s =",
"as utils record = { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s",
"record = { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s = lambda",
"\"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'],",
"lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0)) print(utils.get_name(record['nombre'],",
"{ \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s = lambda record: utils.return_format(record['nombre']",
"\"identidad\": \"30664743\", \"dv\": \"4\" } s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv'])",
"\"30664743\", \"dv\": \"4\" } s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else",
"if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0)) print(utils.get_name(record['nombre'], 1)) print(utils.get_name(record['nombre'], 2))",
"utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0)) print(utils.get_name(record['nombre'], 1)) print(utils.get_name(record['nombre'], 2)) print(utils.get_name(record['nombre'],",
"\"4\" } s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0))",
"DataFlow.Descriptor.utils as utils record = { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" }",
"import DataFlow.Descriptor.utils as utils record = { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\"",
"\"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s = lambda record: utils.return_format(record['nombre'] if",
"record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0)) print(utils.get_name(record['nombre'], 1))",
"} s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record))",
"= lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0))",
"= { \"nombre\": \"<NAME>\", \"identidad\": \"30664743\", \"dv\": \"4\" } s = lambda record:",
"utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'], 0)) print(utils.get_name(record['nombre'], 1)) print(utils.get_name(record['nombre'],",
"\"dv\": \"4\" } s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'],",
"s = lambda record: utils.return_format(record['nombre'] if utils.is_company(record['identidad'], record['dv']) else utils.get_name(record['nombre'], 0)) print(s(record)) print(utils.get_name(record['nombre'],"
] |
[] |
[
"import os def parse_location(location): \"\"\"Extracts latitude and longitude from a location string. Args:",
"Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west = location.split() latitude = float(latitude_str)",
"\"S\" else 1 longitude = float(longitude_str) * -1 if east_west == \"W\" else",
"== \"S\" else 1 longitude = float(longitude_str) * -1 if east_west == \"W\"",
"longitude \"\"\" latitude_str, north_south, longitude_str, east_west = location.split() latitude = float(latitude_str) * -1",
"location string. Args: location: Decimal Degrees (D.D) representation of a geographical location, e.g.",
"latitude_str, north_south, longitude_str, east_west = location.split() latitude = float(latitude_str) * -1 if north_south",
"north_south, longitude_str, east_west = location.split() latitude = float(latitude_str) * -1 if north_south ==",
"def parse_location(location): \"\"\"Extracts latitude and longitude from a location string. Args: location: Decimal",
"location.split() latitude = float(latitude_str) * -1 if north_south == \"S\" else 1 longitude",
"cleaning import os def parse_location(location): \"\"\"Extracts latitude and longitude from a location string.",
"\"\"\"Extracts latitude and longitude from a location string. Args: location: Decimal Degrees (D.D)",
"longitude = float(longitude_str) * -1 if east_west == \"W\" else -1 return latitude,",
"float(latitude_str) * -1 if north_south == \"S\" else 1 longitude = float(longitude_str) *",
"location: Decimal Degrees (D.D) representation of a geographical location, e.g. \"34.56 N 123.45",
"<gh_stars>1-10 # Utilities for data cleaning import os def parse_location(location): \"\"\"Extracts latitude and",
"longitude from a location string. Args: location: Decimal Degrees (D.D) representation of a",
"-1 if north_south == \"S\" else 1 longitude = float(longitude_str) * -1 if",
"a geographical location, e.g. \"34.56 N 123.45 W\" Returns: latitude, longitude \"\"\" latitude_str,",
"if north_south == \"S\" else 1 longitude = float(longitude_str) * -1 if east_west",
"Utilities for data cleaning import os def parse_location(location): \"\"\"Extracts latitude and longitude from",
"geographical location, e.g. \"34.56 N 123.45 W\" Returns: latitude, longitude \"\"\" latitude_str, north_south,",
"and longitude from a location string. Args: location: Decimal Degrees (D.D) representation of",
"123.45 W\" Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west = location.split() latitude",
"\"34.56 N 123.45 W\" Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west =",
"e.g. \"34.56 N 123.45 W\" Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west",
"string. Args: location: Decimal Degrees (D.D) representation of a geographical location, e.g. \"34.56",
"os def parse_location(location): \"\"\"Extracts latitude and longitude from a location string. Args: location:",
"east_west = location.split() latitude = float(latitude_str) * -1 if north_south == \"S\" else",
"a location string. Args: location: Decimal Degrees (D.D) representation of a geographical location,",
"= location.split() latitude = float(latitude_str) * -1 if north_south == \"S\" else 1",
"for data cleaning import os def parse_location(location): \"\"\"Extracts latitude and longitude from a",
"= float(longitude_str) * -1 if east_west == \"W\" else -1 return latitude, longitude_str",
"representation of a geographical location, e.g. \"34.56 N 123.45 W\" Returns: latitude, longitude",
"else 1 longitude = float(longitude_str) * -1 if east_west == \"W\" else -1",
"* -1 if north_south == \"S\" else 1 longitude = float(longitude_str) * -1",
"of a geographical location, e.g. \"34.56 N 123.45 W\" Returns: latitude, longitude \"\"\"",
"latitude and longitude from a location string. Args: location: Decimal Degrees (D.D) representation",
"= float(latitude_str) * -1 if north_south == \"S\" else 1 longitude = float(longitude_str)",
"\"\"\" latitude_str, north_south, longitude_str, east_west = location.split() latitude = float(latitude_str) * -1 if",
"(D.D) representation of a geographical location, e.g. \"34.56 N 123.45 W\" Returns: latitude,",
"data cleaning import os def parse_location(location): \"\"\"Extracts latitude and longitude from a location",
"W\" Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west = location.split() latitude =",
"Degrees (D.D) representation of a geographical location, e.g. \"34.56 N 123.45 W\" Returns:",
"longitude_str, east_west = location.split() latitude = float(latitude_str) * -1 if north_south == \"S\"",
"Args: location: Decimal Degrees (D.D) representation of a geographical location, e.g. \"34.56 N",
"latitude = float(latitude_str) * -1 if north_south == \"S\" else 1 longitude =",
"from a location string. Args: location: Decimal Degrees (D.D) representation of a geographical",
"1 longitude = float(longitude_str) * -1 if east_west == \"W\" else -1 return",
"location, e.g. \"34.56 N 123.45 W\" Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str,",
"Decimal Degrees (D.D) representation of a geographical location, e.g. \"34.56 N 123.45 W\"",
"N 123.45 W\" Returns: latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west = location.split()",
"parse_location(location): \"\"\"Extracts latitude and longitude from a location string. Args: location: Decimal Degrees",
"north_south == \"S\" else 1 longitude = float(longitude_str) * -1 if east_west ==",
"latitude, longitude \"\"\" latitude_str, north_south, longitude_str, east_west = location.split() latitude = float(latitude_str) *",
"# Utilities for data cleaning import os def parse_location(location): \"\"\"Extracts latitude and longitude"
] |
[
"type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ],",
"compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x)",
"x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[],",
") _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE",
"dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds',",
"nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE",
"file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0,",
"'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse',",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False,",
"google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf",
"label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error',",
"_BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0,",
"enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE =",
"from google.protobuf import message as _message from google.protobuf import reflection as _reflection from",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9,",
"extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353,",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1,",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9,",
"serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper',",
"or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message",
"import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor",
"_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor",
"], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor(",
"_BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR)",
"extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114,",
"= _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponseWrapper) })",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False,",
"file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0,",
"extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR,",
"serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST",
"\\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None,",
"-*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT",
"@@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' :",
"_reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse)",
"and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from",
"as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03",
"], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[],",
"serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code',",
"# @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR =",
"has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[],",
"], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70,",
"name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from",
"full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor(",
"= _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) })",
"has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1,",
"from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool",
"@@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' :",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3,",
"as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2",
"}) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2'",
"tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04",
"_BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0,",
"}) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2'",
"\\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[",
"fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None,",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1,",
"serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,])",
"label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ],",
"default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[",
"], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219,",
"= _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1,",
"BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponseWrapper)",
"_sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' #",
") _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code',",
"by the protocol buffer compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto import sys",
"cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data',",
"full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ],",
"index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE",
"reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db =",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9,",
"full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10,",
"number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"_reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponseWrapper) }) _sym_db.RegisterMessage(BatchGetToolDetailResponseWrapper)",
"name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1,",
"import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db",
"_descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None,",
"], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[",
"label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error',",
"DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR'",
"default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2,",
"the protocol buffer compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False,",
"is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type =",
"is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse',",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3',",
"], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL",
"\\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor(",
"has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[],",
"'__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR'",
"name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"= _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' :",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01",
"tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER",
"(lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[",
"_descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None,",
"from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None,",
"full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"# Generated by the protocol buffer compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto",
"_BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest =",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4,",
"serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] =",
"containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None,",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4,",
"DO NOT EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or",
"label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data',",
"_descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03",
"# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO",
"protocol buffer compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and",
"_descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None,",
", dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds',",
"label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ],",
"tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02",
"_descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9,",
"filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False,",
"tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False,",
"_BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2'",
"'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE,",
"syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None,",
"number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"_BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), {",
"serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor(",
"descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection",
"_descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None,",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1,",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11,",
"import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"\\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor(",
"cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error',",
"= _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1,",
"BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest)",
"], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[",
"_BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), {",
"\\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None,",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None,",
"name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1,",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False,",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3,",
"_BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST,",
"name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9,",
"extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest']",
": 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' :",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"= _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic',",
"number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None,",
"full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"_descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2,",
"package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3')",
") _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code',",
"], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor(",
"filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False,",
"index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"\\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST =",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None,",
"full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse']",
"EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))",
"'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER,",
"index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type",
"_BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper']",
"coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT!",
"DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest',",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None,",
"= _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest",
"nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER",
"(_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse",
"DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__'",
"(_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponseWrapper) }) _sym_db.RegisterMessage(BatchGetToolDetailResponseWrapper) #",
"as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as",
"_descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5,",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9,",
"containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None,",
"\\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR,",
"enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER =",
"# @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__'",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9,",
"oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type = tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] =",
"type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ],",
"oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None,",
"fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None,",
"= _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02",
"full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1,",
"cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[",
"# source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3,",
"_BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0,",
"@@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor(",
"cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain',",
"'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper',",
"extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216,",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ],",
"label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain',",
"= tool__sdk_dot_model_dot_tool_dot_tool__pb2._TOOL _BATCHGETTOOLDETAILRESPONSEWRAPPER.fields_by_name['data'].message_type = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailRequest'] = _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] =",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1,",
"(_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper",
"syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') ,",
"serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse',",
"number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"{ 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse =",
"# @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__'",
"_message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database",
"_sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto',",
"_descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"_descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5,",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False,",
"name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error',",
"is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper',",
"google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports)",
"google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import",
"= _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1,",
"DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01",
"index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"Generated by the protocol buffer compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto import",
"= _BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,),",
"nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type",
"'__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR'",
"cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9,",
"extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR,",
"default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[",
"full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"full_name='basic.BatchGetToolDetailRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1,",
"label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message',",
"full_name='basic.BatchGetToolDetailResponse.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"_symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='batch_get_tool_detail.proto', package='basic', syntax='proto3',",
"serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code',",
"fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"_sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' #",
"(lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message',",
"buffer compiler. DO NOT EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda",
"_descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, ) _BATCHGETTOOLDETAILRESPONSE.fields_by_name['data'].message_type =",
"number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse)",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3, type=9, cpp_type=9, label=1,",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False,",
"type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ],",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2, number=3,",
"google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf",
"sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as",
"symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None,",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9,",
"{ 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponseWrapper) }) _sym_db.RegisterMessage(BatchGetToolDetailResponseWrapper) # @@protoc_insertion_point(module_scope)",
"-*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source:",
"oneofs=[ ], serialized_start=116, serialized_end=216, ) _BATCHGETTOOLDETAILRESPONSEWRAPPER = _descriptor.Descriptor( name='BatchGetToolDetailResponseWrapper', full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None,",
"utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! #",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10,",
"], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116, serialized_end=216, )",
"as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default()",
"filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False,",
"\\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest',",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None,",
"{ 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper =",
"message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[],",
"name='batch_get_tool_detail.proto', package='basic', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x1b\\x62\\x61tch_get_tool_detail.proto\\x12\\x05\\x62\\x61sic\\x1a\\x1etool_sdk/model/tool/tool.proto\\\",\\n\\x19\\x42\\x61tchGetToolDetailRequest\\x12\\x0f\\n\\x07toolIds\\x18\\x01 \\x01(\\t\\\"d\\n\\x1a\\x42\\x61tchGetToolDetailResponse\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\r\\n\\x05\\x65rror\\x18\\x02 \\x01(\\t\\x12\\x0f\\n\\x07message\\x18\\x03 \\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04",
"as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as",
"_reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from",
"], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=114, )",
"name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False,",
": 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,), { 'DESCRIPTOR' :",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='basic.BatchGetToolDetailResponse.message', index=2,",
"has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1,",
"\\x01(\\t\\x12\\x18\\n\\x04\\x64\\x61ta\\x18\\x04 \\x03(\\x0b\\x32\\n.tool.Tool\\\"\\x86\\x01\\n!BatchGetToolDetailResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12/\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32!.basic.BatchGetToolDetailResponseb\\x06proto3') , dependencies=[tool__sdk_dot_model_dot_tool_dot_tool__pb2.DESCRIPTOR,]) _BATCHGETTOOLDETAILREQUEST = _descriptor.Descriptor( name='BatchGetToolDetailRequest', full_name='basic.BatchGetToolDetailRequest',",
"file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[",
"= _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' :",
"number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data',",
"import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import",
"type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor(",
"= _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) })",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponse.data', index=3, number=4, type=11,",
"source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf",
"name='toolIds', full_name='basic.BatchGetToolDetailRequest.toolIds', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database #",
"_descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection",
"], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=219, serialized_end=353, )",
"serialized_start=70, serialized_end=114, ) _BATCHGETTOOLDETAILRESPONSE = _descriptor.Descriptor( name='BatchGetToolDetailResponse', full_name='basic.BatchGetToolDetailResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor(",
"label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ],",
": _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest) BatchGetToolDetailResponse = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponse', (_message.Message,),",
"_descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"_reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILREQUEST, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailRequest) }) _sym_db.RegisterMessage(BatchGetToolDetailRequest)",
"_descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3,",
": _BATCHGETTOOLDETAILRESPONSE, '__module__' : 'batch_get_tool_detail_pb2' # @@protoc_insertion_point(class_scope:basic.BatchGetToolDetailResponse) }) _sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,),",
"cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[",
"_sym_db.RegisterMessage(BatchGetToolDetailResponse) BatchGetToolDetailResponseWrapper = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _BATCHGETTOOLDETAILRESPONSEWRAPPER, '__module__' : 'batch_get_tool_detail_pb2' #",
"name='error', full_name='basic.BatchGetToolDetailResponse.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"_symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tool_sdk.model.tool import tool_pb2 as tool__sdk_dot_model_dot_tool_dot_tool__pb2 DESCRIPTOR",
"NOT EDIT! # source: batch_get_tool_detail.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='basic.BatchGetToolDetailResponseWrapper.codeExplain', index=1, number=2, type=9,",
"import message as _message from google.protobuf import reflection as _reflection from google.protobuf import",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"full_name='basic.BatchGetToolDetailResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='basic.BatchGetToolDetailResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1,",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='basic.BatchGetToolDetailResponseWrapper.error', index=2,",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='basic.BatchGetToolDetailResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None,",
"], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=116,",
"_BATCHGETTOOLDETAILREQUEST DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponse'] = _BATCHGETTOOLDETAILRESPONSE DESCRIPTOR.message_types_by_name['BatchGetToolDetailResponseWrapper'] = _BATCHGETTOOLDETAILRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) BatchGetToolDetailRequest = _reflection.GeneratedProtocolMessageType('BatchGetToolDetailRequest', (_message.Message,), {"
] |
[
"and right boundary # in order without duplicate nodes. # # Left boundary",
"output reversed right boundary. # So order them in anti-clockwise without duplicates and",
"the right-most node. If the root doesn't have left # subtree or right",
"nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): # preorder if root: if",
"nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r = TreeNode(1) r.left,",
"subtree or right subtree, then the root itself is left boundary or right",
"right-most node is also defined by the same way with left and right",
"return the values of its boundary in anti-clockwise direction # starting from root.",
"Input: # ____1_____ # / \\ # 2 3 # / \\ /",
"way with left and right exchanged. # Input: # 1 # \\ #",
"rightBoundary(root.right, nodes) return nodes r = TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left,",
"nodes): if root and (root.left or root.right): if not root.right: rightBoundary(root.left, nodes) else:",
"is left boundary or right boundary. # Note this definition only applies to",
"\\ # 2 # / \\ # 3 4 # # Ouput: #",
"are node 1,3,6,10. (10 is the right-most node). # So order them in",
"to the right subtree. Repeat until # you reach a leaf node. #",
"nodes) leaves(root.right, nodes) if not root: return [] nodes = [root.val] leftBoundary(root.left, nodes)",
"path from root to the right-most node. If the root doesn't have left",
"we have [1,3,4,2]. # # Input: # ____1_____ # / \\ # 2",
"# # Left boundary is defined as the path from root to the",
"None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype: List[int] \"\"\"",
"a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left",
"r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6) r.right.left.left,",
"a binary tree, return the values of its boundary in anti-clockwise direction #",
"exchanged. # Input: # 1 # \\ # 2 # / \\ #",
"only applies to the input binary tree, and not applies to any subtrees.",
"\\ # 7 8 9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3] # #",
"method if root and (root.left or root.right): nodes.append(root.val) if not root.left: # only",
"root.right): if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes):",
"binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left =",
"node). # So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].",
"None self.right = None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode",
"return [] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes)",
"not root.left: # only do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def",
"branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root and (root.left",
"3 # / \\ / # 4 5 6 # / \\ /",
"or right subtree, then the root itself is left boundary or right boundary.",
"The right boundary are node 1,3,6,10. (10 is the right-most node). # So",
"to definition) # The leaves are node 4,7,8,9,10. # The right boundary are",
"leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r = TreeNode(1)",
"root doesn't have left # subtree or right subtree, then the root itself",
"# [1, 3, 4, 2] # # Explanation: # The root doesn't have",
"3 and 4. # The right boundary are node 1,2,4. Note the anti-clockwise",
"subtree. Repeat until # you reach a leaf node. # # The right-most",
"subtree, so the root itself is left boundary. # The leaves are node",
"root and (root.left or root.right): if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes)",
"reach a leaf node. # # The right-most node is also defined by",
"as the path from root to the right-most node. If the root doesn't",
"the right subtree. Repeat until # you reach a leaf node. # #",
"you reach a leaf node. # # The right-most node is also defined",
"leaves(root, nodes): # preorder if root: if not root.left and not root.right: nodes.append(root.val)",
"# / \\ # 3 4 # # Ouput: # [1, 3, 4,",
"the input binary tree, and not applies to any subtrees. # # The",
"# Ouput: # [1, 3, 4, 2] # # Explanation: # The root",
"(root.left or root.right): if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def",
"same way with left and right exchanged. # Input: # 1 # \\",
"not applies to any subtrees. # # The left-most node is defined as",
"node. Right boundary # is defined as the path from root to the",
"firstly # travel to the left subtree if exists. If not, travel to",
"left boundary are node 1,2,4. (4 is the left-most node according to definition)",
"leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r = TreeNode(1) r.left, r.right",
"nodes.append(root.val) if not root.left: # only do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left,",
"Note this definition only applies to the input binary tree, and not applies",
"you should output reversed right boundary. # So order them in anti-clockwise without",
"nodes. # # Left boundary is defined as the path from root to",
"without duplicate nodes. # # Left boundary is defined as the path from",
"preorder if root: if not root.left and not root.right: nodes.append(root.val) return leaves(root.left, nodes)",
"return leaves(root.left, nodes) leaves(root.right, nodes) if not root: return [] nodes = [root.val]",
"rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): # preorder if root: if not root.left",
"itself is left boundary or right boundary. # Note this definition only applies",
"# 7 8 9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation:",
"# Given a binary tree, return the values of its boundary in anti-clockwise",
"defined as the path from root to the left-most node. Right boundary #",
"or root.right): nodes.append(root.val) if not root.left: # only do 1 branch leftBoundary(root.right, nodes)",
"boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed",
"Right boundary # is defined as the path from root to the right-most",
"tree, return the values of its boundary in anti-clockwise direction # starting from",
"TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right",
"# Space: O(h) # 545 # Given a binary tree, return the values",
"self.left = None self.right = None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type",
"root.left and not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if not root:",
"# you reach a leaf node. # # The right-most node is also",
"# The leaves are node 4,7,8,9,10. # The right boundary are node 1,3,6,10.",
"node, leaving to leaves() method if root and (root.left or root.right): nodes.append(root.val) if",
"this definition only applies to the input binary tree, and not applies to",
"leaf node you could reach when you always firstly # travel to the",
"defined as the path from root to the right-most node. If the root",
"is left boundary. # The leaves are node 3 and 4. # The",
"left boundary or right boundary. # Note this definition only applies to the",
"so the root itself is left boundary. # The leaves are node 3",
"the left subtree if exists. If not, travel to the right subtree. Repeat",
"[1,2,4,7,8,9,10,6,3] # # Explanation: # The left boundary are node 1,2,4. (4 is",
"left boundary, leaves, and right boundary # in order without duplicate nodes. #",
"exists. If not, travel to the right subtree. Repeat until # you reach",
"TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6) r.right.left.left, r.right.left.right =",
"r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7),",
"if not root.left and not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if",
"anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for a binary tree",
"root to the left-most node. Right boundary # is defined as the path",
"x): self.val = x self.left = None self.right = None class Solution(object): def",
"TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left =",
"(root.left or root.right): nodes.append(root.val) if not root.left: # only do 1 branch leftBoundary(root.right,",
"by the same way with left and right exchanged. # Input: # 1",
"is defined as the path from root to the right-most node. If the",
"nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for a binary tree node. class TreeNode(object):",
"boundary is defined as the path from root to the left-most node. Right",
"don't process leaf node, leaving to leaves() method if root and (root.left or",
"definition only applies to the input binary tree, and not applies to any",
"# The right-most node is also defined by the same way with left",
"return nodes r = TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right =",
"boundary. # So order them in anti-clockwise without duplicates and we have [1,3,4,2].",
"nodes) def rightBoundary(root, nodes): if root and (root.left or root.right): if not root.right:",
"# Input: # 1 # \\ # 2 # / \\ # 3",
"root to the right-most node. If the root doesn't have left # subtree",
"leaving to leaves() method if root and (root.left or root.right): nodes.append(root.val) if not",
"direction means you should output reversed right boundary. # So order them in",
"Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root,",
"values of its boundary in anti-clockwise direction # starting from root. Boundary includes",
"could reach when you always firstly # travel to the left subtree if",
"# So order them in anti-clockwise without duplicates and we have [1,3,4,2]. #",
"# # Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: # The left boundary are",
"def leaves(root, nodes): # preorder if root: if not root.left and not root.right:",
"4,7,8,9,10. # The right boundary are node 1,3,6,10. (10 is the right-most node).",
"we have [1,2,4,7,8,9,10,6,3]. # Definition for a binary tree node. class TreeNode(object): def",
"reach when you always firstly # travel to the left subtree if exists.",
"2] # # Explanation: # The root doesn't have left subtree, so the",
"def leftBoundary(root, nodes): # don't process leaf node, leaving to leaves() method if",
"\\ / # 4 5 6 # / \\ / \\ # 7",
"# # The right-most node is also defined by the same way with",
"duplicate nodes. # # Left boundary is defined as the path from root",
"# don't process leaf node, leaving to leaves() method if root and (root.left",
"4 5 6 # / \\ / \\ # 7 8 9 10",
"\"\"\" :type root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes): # don't process",
"TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes): # don't process leaf node, leaving",
"# 1 # \\ # 2 # / \\ # 3 4 #",
"# 545 # Given a binary tree, return the values of its boundary",
"and (root.left or root.right): if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val)",
"are node 1,2,4. (4 is the left-most node according to definition) # The",
"tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None",
"[1,2,4,7,8,9,10,6,3]. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x):",
"8 9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: # The",
"x self.left = None self.right = None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\"",
"them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for a",
"includes left boundary, leaves, and right boundary # in order without duplicate nodes.",
"nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if not root: return [] nodes =",
"\\ / \\ # 7 8 9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3]",
"= None self.right = None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root:",
"# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val",
"right boundary are node 1,2,4. Note the anti-clockwise direction means you should output",
"subtrees. # # The left-most node is defined as a leaf node you",
"leftBoundary(root, nodes): # don't process leaf node, leaving to leaves() method if root",
"Repeat until # you reach a leaf node. # # The right-most node",
"subtree if exists. If not, travel to the right subtree. Repeat until #",
"the root itself is left boundary or right boundary. # Note this definition",
"if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): #",
"leaf node, leaving to leaves() method if root and (root.left or root.right): nodes.append(root.val)",
"nodes) return nodes r = TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right",
"do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root",
"If the root doesn't have left # subtree or right subtree, then the",
"a leaf node. # # The right-most node is also defined by the",
"nodes) rightBoundary(root.right, nodes) return nodes r = TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3)",
"____1_____ # / \\ # 2 3 # / \\ / # 4",
"direction # starting from root. Boundary includes left boundary, leaves, and right boundary",
"leaves() method if root and (root.left or root.right): nodes.append(root.val) if not root.left: #",
"root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if not root: return [] nodes",
"So order them in anti-clockwise without duplicates and we have [1,3,4,2]. # #",
"/ # 4 5 6 # / \\ / \\ # 7 8",
"# travel to the left subtree if exists. If not, travel to the",
"if not root.left: # only do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes)",
"9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: # The left",
"(4 is the left-most node according to definition) # The leaves are node",
"according to definition) # The leaves are node 4,7,8,9,10. # The right boundary",
"/ \\ # 3 4 # # Ouput: # [1, 3, 4, 2]",
"left boundary. # The leaves are node 3 and 4. # The right",
"# The root doesn't have left subtree, so the root itself is left",
"order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for",
"and we have [1,3,4,2]. # # Input: # ____1_____ # / \\ #",
"until # you reach a leaf node. # # The right-most node is",
"of its boundary in anti-clockwise direction # starting from root. Boundary includes left",
"you always firstly # travel to the left subtree if exists. If not,",
"node is also defined by the same way with left and right exchanged.",
"Ouput: # [1, 3, 4, 2] # # Explanation: # The root doesn't",
"the same way with left and right exchanged. # Input: # 1 #",
"The leaves are node 3 and 4. # The right boundary are node",
"3 4 # # Ouput: # [1, 3, 4, 2] # # Explanation:",
"a leaf node you could reach when you always firstly # travel to",
"defined by the same way with left and right exchanged. # Input: #",
"boundary. # Note this definition only applies to the input binary tree, and",
"[] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return",
"[1, 3, 4, 2] # # Explanation: # The root doesn't have left",
"[1,3,4,2]. # # Input: # ____1_____ # / \\ # 2 3 #",
"root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): # preorder if",
"duplicates and we have [1,3,4,2]. # # Input: # ____1_____ # / \\",
"# only do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes):",
"nodes r = TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4),",
"nodes) if not root: return [] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes)",
"to leaves() method if root and (root.left or root.right): nodes.append(root.val) if not root.left:",
"left subtree if exists. If not, travel to the right subtree. Repeat until",
"have left # subtree or right subtree, then the root itself is left",
"boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes): #",
"is the left-most node according to definition) # The leaves are node 4,7,8,9,10.",
"root.right): nodes.append(root.val) if not root.left: # only do 1 branch leftBoundary(root.right, nodes) else:",
"def rightBoundary(root, nodes): if root and (root.left or root.right): if not root.right: rightBoundary(root.left,",
"only do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if",
"The leaves are node 4,7,8,9,10. # The right boundary are node 1,3,6,10. (10",
"# # Ouput: # [1, 3, 4, 2] # # Explanation: # The",
"r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6)",
"2 # / \\ # 3 4 # # Ouput: # [1, 3,",
"# in order without duplicate nodes. # # Left boundary is defined as",
"nodes) nodes.append(root.val) def leaves(root, nodes): # preorder if root: if not root.left and",
"boundary, leaves, and right boundary # in order without duplicate nodes. # #",
"applies to the input binary tree, and not applies to any subtrees. #",
"10 # # Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: # The left boundary",
"not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): # preorder",
"left-most node is defined as a leaf node you could reach when you",
"Space: O(h) # 545 # Given a binary tree, return the values of",
"not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if not root: return []",
"1 # \\ # 2 # / \\ # 3 4 # #",
"nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes",
"you could reach when you always firstly # travel to the left subtree",
"1,2,4. (4 is the left-most node according to definition) # The leaves are",
"# ____1_____ # / \\ # 2 3 # / \\ / #",
"boundary # is defined as the path from root to the right-most node.",
"TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left",
"node. # # The right-most node is also defined by the same way",
"not root: return [] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes)",
"the anti-clockwise direction means you should output reversed right boundary. # So order",
"node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary.",
"3, 4, 2] # # Explanation: # The root doesn't have left subtree,",
"if exists. If not, travel to the right subtree. Repeat until # you",
"as the path from root to the left-most node. Right boundary # is",
"\"\"\" def leftBoundary(root, nodes): # don't process leaf node, leaving to leaves() method",
"4, 2] # # Explanation: # The root doesn't have left subtree, so",
"to the left-most node. Right boundary # is defined as the path from",
"# \\ # 2 # / \\ # 3 4 # # Ouput:",
"root itself is left boundary or right boundary. # Note this definition only",
"The right boundary are node 1,2,4. Note the anti-clockwise direction means you should",
"if root: if not root.left and not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right,",
"nodes.append(root.val) def leaves(root, nodes): # preorder if root: if not root.left and not",
"input binary tree, and not applies to any subtrees. # # The left-most",
"class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right =",
"is the right-most node). # So order them in anti-clockwise without duplicate nodes",
"process leaf node, leaving to leaves() method if root and (root.left or root.right):",
"Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: # The left boundary are node 1,2,4.",
"nodes): # don't process leaf node, leaving to leaves() method if root and",
"node 1,3,6,10. (10 is the right-most node). # So order them in anti-clockwise",
"also defined by the same way with left and right exchanged. # Input:",
"node. If the root doesn't have left # subtree or right subtree, then",
"right-most node). # So order them in anti-clockwise without duplicate nodes we have",
"Note the anti-clockwise direction means you should output reversed right boundary. # So",
"doesn't have left # subtree or right subtree, then the root itself is",
"# Explanation: # The left boundary are node 1,2,4. (4 is the left-most",
"always firstly # travel to the left subtree if exists. If not, travel",
"not, travel to the right subtree. Repeat until # you reach a leaf",
"root doesn't have left subtree, so the root itself is left boundary. #",
"rightBoundary(root, nodes): if root and (root.left or root.right): if not root.right: rightBoundary(root.left, nodes)",
"Given a binary tree, return the values of its boundary in anti-clockwise direction",
"node is defined as a leaf node you could reach when you always",
"root itself is left boundary. # The leaves are node 3 and 4.",
"starting from root. Boundary includes left boundary, leaves, and right boundary # in",
"leaves are node 3 and 4. # The right boundary are node 1,2,4.",
"nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root and (root.left or root.right):",
"are node 3 and 4. # The right boundary are node 1,2,4. Note",
"root): \"\"\" :type root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes): # don't",
"The right-most node is also defined by the same way with left and",
"Time: O(n) # Space: O(h) # 545 # Given a binary tree, return",
"right boundary. # Note this definition only applies to the input binary tree,",
"duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for a binary tree node. class",
"# [1,2,4,7,8,9,10,6,3] # # Explanation: # The left boundary are node 1,2,4. (4",
"def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes):",
"[root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r =",
"anti-clockwise direction means you should output reversed right boundary. # So order them",
"and right exchanged. # Input: # 1 # \\ # 2 # /",
"Boundary includes left boundary, leaves, and right boundary # in order without duplicate",
"r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6) r.right.left.left, r.right.left.right = TreeNode(9), TreeNode(10)",
"order without duplicate nodes. # # Left boundary is defined as the path",
"right exchanged. # Input: # 1 # \\ # 2 # / \\",
"left-most node according to definition) # The leaves are node 4,7,8,9,10. # The",
"rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): # preorder if root:",
"root. Boundary includes left boundary, leaves, and right boundary # in order without",
"to the left subtree if exists. If not, travel to the right subtree.",
":rtype: List[int] \"\"\" def leftBoundary(root, nodes): # don't process leaf node, leaving to",
"as a leaf node you could reach when you always firstly # travel",
"Explanation: # The left boundary are node 1,2,4. (4 is the left-most node",
"the left-most node according to definition) # The leaves are node 4,7,8,9,10. #",
"to any subtrees. # # The left-most node is defined as a leaf",
"The root doesn't have left subtree, so the root itself is left boundary.",
"the root doesn't have left # subtree or right subtree, then the root",
"have left subtree, so the root itself is left boundary. # The leaves",
"is also defined by the same way with left and right exchanged. #",
"and not applies to any subtrees. # # The left-most node is defined",
"itself is left boundary. # The leaves are node 3 and 4. #",
"applies to any subtrees. # # The left-most node is defined as a",
"and 4. # The right boundary are node 1,2,4. Note the anti-clockwise direction",
"if not root: return [] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right,",
"anti-clockwise direction # starting from root. Boundary includes left boundary, leaves, and right",
"not root.left and not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if not",
"travel to the left subtree if exists. If not, travel to the right",
"So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition",
"# # The left-most node is defined as a leaf node you could",
"with left and right exchanged. # Input: # 1 # \\ # 2",
"its boundary in anti-clockwise direction # starting from root. Boundary includes left boundary,",
"are node 4,7,8,9,10. # The right boundary are node 1,3,6,10. (10 is the",
"# / \\ / \\ # 7 8 9 10 # # Ouput:",
"# Time: O(n) # Space: O(h) # 545 # Given a binary tree,",
"the values of its boundary in anti-clockwise direction # starting from root. Boundary",
"Left boundary is defined as the path from root to the left-most node.",
"nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r = TreeNode(1) r.left, r.right =",
"leaves(root.right, nodes) if not root: return [] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left,",
"boundary # in order without duplicate nodes. # # Left boundary is defined",
"# Note this definition only applies to the input binary tree, and not",
"If not, travel to the right subtree. Repeat until # you reach a",
"tree, and not applies to any subtrees. # # The left-most node is",
"is defined as the path from root to the left-most node. Right boundary",
"subtree, then the root itself is left boundary or right boundary. # Note",
"order them in anti-clockwise without duplicates and we have [1,3,4,2]. # # Input:",
"# 2 # / \\ # 3 4 # # Ouput: # [1,",
"and not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes) if not root: return",
"r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6) r.right.left.left, r.right.left.right = TreeNode(9), TreeNode(10) print(Solution().boundaryOfBinaryTree(r))",
"is defined as a leaf node you could reach when you always firstly",
"# The right boundary are node 1,2,4. Note the anti-clockwise direction means you",
"travel to the right subtree. Repeat until # you reach a leaf node.",
"r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right =",
"root.left: # only do 1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root,",
"class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype: List[int] \"\"\" def",
"and (root.left or root.right): nodes.append(root.val) if not root.left: # only do 1 branch",
"left-most node. Right boundary # is defined as the path from root to",
"anti-clockwise without duplicates and we have [1,3,4,2]. # # Input: # ____1_____ #",
"or root.right): if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root,",
"1 branch leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root and",
"# 4 5 6 # / \\ / \\ # 7 8 9",
"# # Explanation: # The root doesn't have left subtree, so the root",
"# The leaves are node 3 and 4. # The right boundary are",
"nodes): # preorder if root: if not root.left and not root.right: nodes.append(root.val) return",
"root and (root.left or root.right): nodes.append(root.val) if not root.left: # only do 1",
"# / \\ / # 4 5 6 # / \\ / \\",
"leaves are node 4,7,8,9,10. # The right boundary are node 1,3,6,10. (10 is",
"means you should output reversed right boundary. # So order them in anti-clockwise",
"leaves(root.left, nodes) leaves(root.right, nodes) if not root: return [] nodes = [root.val] leftBoundary(root.left,",
"TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6) r.right.left.left, r.right.left.right = TreeNode(9),",
"TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None",
"path from root to the left-most node. Right boundary # is defined as",
"Input: # 1 # \\ # 2 # / \\ # 3 4",
"= None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype: List[int]",
"r = TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5)",
"have [1,3,4,2]. # # Input: # ____1_____ # / \\ # 2 3",
"\\ # 2 3 # / \\ / # 4 5 6 #",
"# 2 3 # / \\ / # 4 5 6 # /",
"from root. Boundary includes left boundary, leaves, and right boundary # in order",
"# 3 4 # # Ouput: # [1, 3, 4, 2] # #",
"left subtree, so the root itself is left boundary. # The leaves are",
"the path from root to the right-most node. If the root doesn't have",
"leaf node. # # The right-most node is also defined by the same",
"in order without duplicate nodes. # # Left boundary is defined as the",
"or right boundary. # Note this definition only applies to the input binary",
"2 3 # / \\ / # 4 5 6 # / \\",
"defined as a leaf node you could reach when you always firstly #",
"# # Input: # ____1_____ # / \\ # 2 3 # /",
"right-most node. If the root doesn't have left # subtree or right subtree,",
"# Left boundary is defined as the path from root to the left-most",
"binary tree, return the values of its boundary in anti-clockwise direction # starting",
"self.val = x self.left = None self.right = None class Solution(object): def boundaryOfBinaryTree(self,",
"= TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8)",
"definition) # The leaves are node 4,7,8,9,10. # The right boundary are node",
"# starting from root. Boundary includes left boundary, leaves, and right boundary #",
"node 1,2,4. (4 is the left-most node according to definition) # The leaves",
"reversed right boundary. # So order them in anti-clockwise without duplicates and we",
"from root to the left-most node. Right boundary # is defined as the",
"boundary in anti-clockwise direction # starting from root. Boundary includes left boundary, leaves,",
"root: if not root.left and not root.right: nodes.append(root.val) return leaves(root.left, nodes) leaves(root.right, nodes)",
"without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for a binary tree node.",
"right boundary. # So order them in anti-clockwise without duplicates and we have",
":type root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes): # don't process leaf",
"List[int] \"\"\" def leftBoundary(root, nodes): # don't process leaf node, leaving to leaves()",
"right boundary are node 1,3,6,10. (10 is the right-most node). # So order",
"for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x",
"any subtrees. # # The left-most node is defined as a leaf node",
"6 # / \\ / \\ # 7 8 9 10 # #",
"leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root and (root.left or",
"the left-most node. Right boundary # is defined as the path from root",
"root: TreeNode :rtype: List[int] \"\"\" def leftBoundary(root, nodes): # don't process leaf node,",
"self.right = None class Solution(object): def boundaryOfBinaryTree(self, root): \"\"\" :type root: TreeNode :rtype:",
"# Explanation: # The root doesn't have left subtree, so the root itself",
"node 3 and 4. # The right boundary are node 1,2,4. Note the",
"in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. # Definition for a binary",
"The left boundary are node 1,2,4. (4 is the left-most node according to",
"= TreeNode(1) r.left, r.right = TreeNode(2), TreeNode(3) r.left.left, r.left.right = TreeNode(4), TreeNode(5) r.left.right.left,",
"if root and (root.left or root.right): nodes.append(root.val) if not root.left: # only do",
"# So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3]. #",
"else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root and (root.left or root.right): if",
"leftBoundary(root.left, nodes) def rightBoundary(root, nodes): if root and (root.left or root.right): if not",
"= x self.left = None self.right = None class Solution(object): def boundaryOfBinaryTree(self, root):",
"Explanation: # The root doesn't have left subtree, so the root itself is",
"4. # The right boundary are node 1,2,4. Note the anti-clockwise direction means",
"without duplicates and we have [1,3,4,2]. # # Input: # ____1_____ # /",
"# Input: # ____1_____ # / \\ # 2 3 # / \\",
"4 # # Ouput: # [1, 3, 4, 2] # # Explanation: #",
"boundary or right boundary. # Note this definition only applies to the input",
"def __init__(self, x): self.val = x self.left = None self.right = None class",
"= [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r",
"# The left-most node is defined as a leaf node you could reach",
"are node 1,2,4. Note the anti-clockwise direction means you should output reversed right",
"# preorder if root: if not root.left and not root.right: nodes.append(root.val) return leaves(root.left,",
"root: return [] nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) leaves(root.right, nodes) rightBoundary(root.right,",
"# The left boundary are node 1,2,4. (4 is the left-most node according",
"\\ # 3 4 # # Ouput: # [1, 3, 4, 2] #",
"in anti-clockwise without duplicates and we have [1,3,4,2]. # # Input: # ____1_____",
"the right-most node). # So order them in anti-clockwise without duplicate nodes we",
"O(h) # 545 # Given a binary tree, return the values of its",
"7 8 9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: #",
"have [1,2,4,7,8,9,10,6,3]. # Definition for a binary tree node. class TreeNode(object): def __init__(self,",
"__init__(self, x): self.val = x self.left = None self.right = None class Solution(object):",
"node according to definition) # The leaves are node 4,7,8,9,10. # The right",
"boundary are node 1,3,6,10. (10 is the right-most node). # So order them",
"5 6 # / \\ / \\ # 7 8 9 10 #",
"# # Explanation: # The left boundary are node 1,2,4. (4 is the",
"to the right-most node. If the root doesn't have left # subtree or",
"1,3,6,10. (10 is the right-most node). # So order them in anti-clockwise without",
"= TreeNode(4), TreeNode(5) r.left.right.left, r.left.right.right = TreeNode(7), TreeNode(8) r.right.left = TreeNode(6) r.right.left.left, r.right.left.right",
"doesn't have left subtree, so the root itself is left boundary. # The",
"right boundary # in order without duplicate nodes. # # Left boundary is",
"# / \\ # 2 3 # / \\ / # 4 5",
"them in anti-clockwise without duplicates and we have [1,3,4,2]. # # Input: #",
"/ \\ # 7 8 9 10 # # Ouput: # [1,2,4,7,8,9,10,6,3] #",
"/ \\ # 2 3 # / \\ / # 4 5 6",
"then the root itself is left boundary or right boundary. # Note this",
"to the input binary tree, and not applies to any subtrees. # #",
"else: rightBoundary(root.right, nodes) nodes.append(root.val) def leaves(root, nodes): # preorder if root: if not",
"the path from root to the left-most node. Right boundary # is defined",
"leaves, and right boundary # in order without duplicate nodes. # # Left",
"# The right boundary are node 1,3,6,10. (10 is the right-most node). #",
"/ \\ / # 4 5 6 # / \\ / \\ #",
"binary tree, and not applies to any subtrees. # # The left-most node",
"boundary are node 1,2,4. (4 is the left-most node according to definition) #",
"from root to the right-most node. If the root doesn't have left #",
"the root itself is left boundary. # The leaves are node 3 and",
"leaves(root.right, nodes) rightBoundary(root.right, nodes) return nodes r = TreeNode(1) r.left, r.right = TreeNode(2),",
"The left-most node is defined as a leaf node you could reach when",
"1,2,4. Note the anti-clockwise direction means you should output reversed right boundary. #",
"in anti-clockwise direction # starting from root. Boundary includes left boundary, leaves, and",
"left # subtree or right subtree, then the root itself is left boundary",
"right subtree, then the root itself is left boundary or right boundary. #",
"boundary. # The leaves are node 3 and 4. # The right boundary",
"node you could reach when you always firstly # travel to the left",
"# subtree or right subtree, then the root itself is left boundary or",
"/ \\ / \\ # 7 8 9 10 # # Ouput: #",
"# is defined as the path from root to the right-most node. If",
"(10 is the right-most node). # So order them in anti-clockwise without duplicate",
"should output reversed right boundary. # So order them in anti-clockwise without duplicates",
"if root and (root.left or root.right): if not root.right: rightBoundary(root.left, nodes) else: rightBoundary(root.right,",
"right subtree. Repeat until # you reach a leaf node. # # The",
"left and right exchanged. # Input: # 1 # \\ # 2 #",
"node 4,7,8,9,10. # The right boundary are node 1,3,6,10. (10 is the right-most",
"node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right",
"when you always firstly # travel to the left subtree if exists. If",
"O(n) # Space: O(h) # 545 # Given a binary tree, return the",
"Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val =",
"# Ouput: # [1,2,4,7,8,9,10,6,3] # # Explanation: # The left boundary are node",
"545 # Given a binary tree, return the values of its boundary in"
] |
[
"class Meta: model = Question fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class",
"\"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields = (\"title\", \"body\",",
"\"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields =",
"class Meta: model = Question fields = ( \"title\", \"body\", \"format\", \"answer\", \"release_date\",",
"serializers from codechallenges.models import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question",
"codechallenges.models import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields =",
"Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ( \"title\", \"body\",",
"\"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields = (\"email\", \"correct\",",
"(\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields = (\"email\",",
"class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields = (\"email\", \"correct\", \"answer\", \"question\")",
") class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields = (\"title\", \"body\", \"format\")",
"Question fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission",
"Meta: model = Question fields = ( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\",",
"import serializers from codechallenges.models import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model =",
"= Question fields = ( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class",
"QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer):",
"\"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model =",
"Meta: model = Question fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta:",
"\"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question",
"class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ( \"title\", \"body\", \"format\",",
"= Question fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model =",
"\"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields",
"from rest_framework import serializers from codechallenges.models import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta:",
"model = Question fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model",
"\"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields = (\"title\",",
"model = Question fields = ( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", )",
"fields = (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields",
"Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ( \"title\",",
"QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ( \"title\", \"body\", \"format\", \"answer\",",
"( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model",
"rest_framework import serializers from codechallenges.models import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model",
"= (\"title\", \"body\", \"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields =",
"from codechallenges.models import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields",
"Question fields = ( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer):",
"\"format\") class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields = (\"email\", \"correct\", \"answer\",",
"import Question, Submission class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = (",
"class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta: model = Question fields = (\"title\", \"body\", \"format\") class",
"fields = ( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class",
"= ( \"title\", \"body\", \"format\", \"answer\", \"release_date\", \"expiration_date\", ) class QuestionHiddenSerializer(serializers.ModelSerializer): class Meta:"
] |
[
"not found of the machine. \"\"\" def decorator(f): dec = pytest.mark.skipif( which(name) is",
"import pytest def requires(name: str): \"\"\" A decorator for pytest tests that skips",
"which import pytest def requires(name: str): \"\"\" A decorator for pytest tests that",
"the test if a program with the given name is not found of",
"= pytest.mark.skipif( which(name) is None, reason=f\"Requires program {name!r}\", ) return dec(f) return decorator",
"test if a program with the given name is not found of the",
"the given name is not found of the machine. \"\"\" def decorator(f): dec",
"skips the test if a program with the given name is not found",
"def decorator(f): dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires program {name!r}\", ) return",
"given name is not found of the machine. \"\"\" def decorator(f): dec =",
"tests that skips the test if a program with the given name is",
"the machine. \"\"\" def decorator(f): dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires program",
"for pytest tests that skips the test if a program with the given",
"dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires program {name!r}\", ) return dec(f) return",
"str): \"\"\" A decorator for pytest tests that skips the test if a",
"a program with the given name is not found of the machine. \"\"\"",
"\"\"\" def decorator(f): dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires program {name!r}\", )",
"<gh_stars>1-10 from __future__ import annotations from shutil import which import pytest def requires(name:",
"found of the machine. \"\"\" def decorator(f): dec = pytest.mark.skipif( which(name) is None,",
"A decorator for pytest tests that skips the test if a program with",
"is not found of the machine. \"\"\" def decorator(f): dec = pytest.mark.skipif( which(name)",
"\"\"\" A decorator for pytest tests that skips the test if a program",
"pytest tests that skips the test if a program with the given name",
"from shutil import which import pytest def requires(name: str): \"\"\" A decorator for",
"import annotations from shutil import which import pytest def requires(name: str): \"\"\" A",
"__future__ import annotations from shutil import which import pytest def requires(name: str): \"\"\"",
"of the machine. \"\"\" def decorator(f): dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires",
"that skips the test if a program with the given name is not",
"decorator(f): dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires program {name!r}\", ) return dec(f)",
"pytest def requires(name: str): \"\"\" A decorator for pytest tests that skips the",
"import which import pytest def requires(name: str): \"\"\" A decorator for pytest tests",
"requires(name: str): \"\"\" A decorator for pytest tests that skips the test if",
"if a program with the given name is not found of the machine.",
"with the given name is not found of the machine. \"\"\" def decorator(f):",
"name is not found of the machine. \"\"\" def decorator(f): dec = pytest.mark.skipif(",
"from __future__ import annotations from shutil import which import pytest def requires(name: str):",
"annotations from shutil import which import pytest def requires(name: str): \"\"\" A decorator",
"def requires(name: str): \"\"\" A decorator for pytest tests that skips the test",
"decorator for pytest tests that skips the test if a program with the",
"program with the given name is not found of the machine. \"\"\" def",
"shutil import which import pytest def requires(name: str): \"\"\" A decorator for pytest",
"machine. \"\"\" def decorator(f): dec = pytest.mark.skipif( which(name) is None, reason=f\"Requires program {name!r}\","
] |
[
"side_cc = 90.0 for side_aa in (1.0e-12, 1.0e-10): for ang_B in (23, 90,",
"side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 0, B = various,",
"180 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: #",
"= 90, unknownAng # if a nearly 180: expect C = 90, b",
"opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in testData: if len(expectedOutput) < 4:",
"~0 any !pole 0 side_cc 180-ang_B ~180 any ~0 unknown(90) 180 unknown(90) ~180",
"sinA * sinb) # with some tweaks to handle the other quadrants ang_B",
"nearly 180 (modulo 360): expect C = 90, b = 0, A =",
"(modulo 360) and side_aa is not ang_A = ang_B side_bb = 180.0 -",
"B for side_aa in (-Eps, 0.0, Eps): for ang_B in (0.0, Eps, 32.0,",
"sin_h_B * sin_h_A # numerator and denominator for analogy for bb - aa",
"varies but not nearly 0 or 360, c fairly small but >> Eps",
"case \"unknownAng\" = true, ang_A = ang_C = 90.0. Also side_bb = 0.0,",
"atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if",
"for side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if side_aa",
"den1 = sin_h_B * cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2 = sin_h_B",
"% 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs(side_cc %",
"if a nearly 0 (modulo 360): expect C = 90, b = 180,",
"ang_B !pole any ~0 180-ang_B side_aa 0 !pole any ~180 ang_B 180-side_aa 180",
"for side_aa in (-Eps, 0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0,",
"180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a = 90, B varies but not",
"180 and ang_A and ang_C unknown. Improved accuracy in some corner cases; all",
"code and unit test were incorrect - side_aa normal + side_cc tiny: table",
"# side_cc is not nearly 0 or 180 (modulo 360) ang_A = 180.0",
"c using Napier's analogies # - # compute sin((aa +/- cc) / 2)",
"= cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc",
"0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc =",
"90, b = 0, C = 90, unknown # if c << a:",
"Eps, 180, 180 + Eps, 256, 359): expRes = (0.0, side_cc + (side_aa",
"# a = 90, B varies but not nearly 0 or 360, c",
"0.0 side_bb = side_cc - side_aa ang_C = 180.0 else: # + #",
"((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ]",
"180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_cc in (180.0,",
"~180 ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa",
"two angles and the side connecting them, given the remaining quantities. Inputs: -",
"list of entries, each consisting of: # - the input argument # -",
"cos_h_B * cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A +",
"0 and not nearly 180 (modulo 360) - unknown(90) means unknownAng is set",
"where tan((a +/- c) / 2) = num/den num1 = cos_h_B * cos_h_diff_aacc",
"b = 0, C = 90, unknown # if c << a: expect",
"(180.0 - Eps, 180.0): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0",
"180.0, 90.0, True) else: expRes = (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B,",
"procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput)",
"opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo 360) if abs(side_aa - side_cc) <",
"nearly 0 or 180 (modulo 360) ang_A = 180.0 side_bb = 180.0 -",
"side_cc is nearly 0 (modulo 360) return (90.0, 180.0, 90.0, True) else: #",
"small # to accurately determine angle = atan2 (num, den), give up if",
"< EpsTest: expRes = (90.0, 180.0, 90.0, True) elif 180.0 - side_aa <",
"False) if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest",
"cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA",
"True) else: expRes = (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes))",
"side_cc normal: special case table, code and unit test were incorrect - side_aa",
"sin_h_B * sin_h_sum_aacc # if numerator and denominator are too small # to",
"after side_aa and side_cc special cases. Tweaked the documentation to clarify the special",
"ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~ 180, B = various, c",
"expect C = 90, b = 0, A = 90, unknownAng # else:",
"nearly 0 (modulo 360): expect C = 90, b = 0, A =",
"instead of 0. Bug fix: in some cases side_bb may be 180 and",
"# expect: A = 180 - B, b = a + c cos(B),",
"= opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle",
"(90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return",
"the remaining quantities. Inputs: - side_aa side aa; range of sides: [0, 180]",
"or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't",
"and denominator for analogy for bb - aa num3 = sin_h_cc * sin_h_diff_BA",
"sin((aa +/- cc) / 2) and cos((aa +/- cc) / 2) sin_h_sum_aacc =",
"360) and side_aa is not ang_A = 180.0 - ang_B side_bb = side_aa",
"aa num4 = sin_h_cc * cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA # compute",
"ROwen Changed output zero_bb to unknownAng; side_bb may be 180 instead of 0.",
"side_aa is not ang_A = ang_B side_bb = 180.0 - side_aa ang_C =",
"unit test had errors 2011-01-28 ROwen Bug fix: unknownAng should always be true",
"ValueError - If side bb is near 0 or 180 (see Special Cases",
"* opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb,",
"and the value of side_bb is correct to within epsilon. - all relations",
"+ a cos(B), A ~= 0 side_cc = 90.0 for side_aa in (1.0e-12,",
"expRes)) # c ~ 0, B = various, a various: # if a",
"+ (False,) actualOutput = angSideAng(*testInput) # to handle angles comparing things like 359.999...",
"# - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A *",
"0 (modulo 360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0",
"0, A = 90, unknownAng # else: expect A = 180, b =",
"nearly 180 (modulo 360) - unknown(90) means unknownAng is set True and the",
"cos_h_cc + sin_h_aa * sin_h_cc # compute numerator and denominator, where tan((a +/-",
"cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5)",
"360) - unknown(90) means unknownAng is set True and the angle is unknown",
"% 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((180.0 -",
"unknownAng # else: expect A = 180 - B, b = a, C",
"(89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658,",
"A = 90, b = 0, C = 90, unknown # if c",
"tiny: table was right but code and unit test had errors 2011-01-28 ROwen",
"if c << a: expect A = 180, b = c - a,",
"expRes)) # a ~ 180, B = various, c various: # if c",
"B = various, c various: # if c nearly 180 (modulo 360): expect",
"side_aa normal + side_cc tiny: table was right but code and unit test",
"the inputs are too small to allow computation, raises ValueError - If side",
"0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo",
"Napier's analogy for bb - aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3)",
"to 90 degrees. The sum of ang_A and ang_C is correct and the",
"+/- c) / 2) = num/den num1 = cos_h_B * cos_h_diff_aacc den1 =",
"360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((side_cc - 180)",
"side_cc is not nearly 0 or 180 ang_A = 0.0 side_bb = side_cc",
"(0.0, side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a",
"and cos of ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if",
"unknown and is abitrarily set to 90 degrees. The sum of ang_A and",
"to False) # a ~ 0, B = various, c various: # if",
"ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a",
"* cos_h_sum_BA # compute side bb if abs (num3) + abs (den3) >",
"180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo 360) if",
"unit tests. 2010-08-04 ROwen Bug fix: mis-handled two cases: - side_aa tiny +",
"cos_h_B * sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc # if numerator and denominator",
"Special Cases below for when this occurs) then angles a and c cannot",
"cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print",
"90.0, True) else: expRes = (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc),",
"(270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934,",
"not ang_A = 180.0 - ang_B side_bb = side_aa ang_C = 0.0 elif",
"+ # compute angles a and c using Napier's analogies # - #",
"sin_h_aa * sin_h_cc # compute numerator and denominator, where tan((a +/- c) /",
"is nearly zero (modulo 360) and side_aa is not ang_A = 180.0 -",
"A = 90, unknownAng # else: expect A = 180, b = 180",
"containing: - ang_A angle a - side_bb side bb - ang_C angle c",
"# if c nearly 180 (modulo 360): expect C = 90, b =",
"If the inputs are too small to allow computation, raises ValueError - If",
"47.0, Eps, 0.0): if abs(side_aa % 360.0) < EpsTest: expRes = (90.0, 0.0,",
"set to 90); bb will be 0 or 180 Error Conditions: - If",
"num2 = cos_h_B * sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc # if numerator",
"- Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa % 360.0) < EpsTest: expRes",
"((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135,",
"of ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual,",
"any not small, c = any not small: # if c != a:",
"0 any ~0 >side_aa 0 side_cc-aa 180 where: - !pole means not nearly",
"and c cannot be computed. In this case \"unknownAng\" = true, ang_A =",
"are too small # to accurately determine angle = atan2 (num, den), give",
"sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa",
"Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle: B = 90, a and",
"Eps, 0.0): if side_aa < EpsTest: expRes = (90.0, 180.0, 90.0, True) elif",
"+ (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly small",
"~ 180, B = various, a various: # if a nearly 0 (modulo",
"cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc",
"h_sum_AC + h_diff_AC ang_C = h_sum_AC - h_diff_AC # + # compute side",
"= 0, A = 90, unknownAng # if c nearly 0 (modulo 360):",
"in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if side_aa < EpsTest:",
"is also essentially correct. Special Cases (in the order they are handled): side_aa",
"in some cases side_bb may be 180 and ang_A and ang_C unknown. Improved",
"side_cc in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C",
"Greatly expanded the unit tests. 2010-08-04 ROwen Bug fix: mis-handled two cases: -",
"+ cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc",
"and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) #",
"# else: expect A = 180 - B, b = a, C =",
"true, ang_A = ang_C = 90.0. Also side_bb = 0.0, which is essentially",
"not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)),",
"den2 =\", num1, den1, num2, den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC",
"= cos_h_B * sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc # if numerator and",
"180.0 side_bb = 180.0 - side_cc ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy:",
"A = 90, unknownAng # else: expect A = 0, b = a",
"(den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))):",
"below for when this occurs) then angles a and c cannot be computed.",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # B small, a = any not small, c",
"90, 110.0, 179.0): for side_cc in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A",
"180 - B, b = c + a cos(B), A ~= 0 side_cc",
"- aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb",
"2) and cos((aa +/- cc) / 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc +",
"side bb using one of two Napier's analogies # (one is for bb",
"90.0, True) else: expRes = (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc),",
"testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData += [ # 90/90/90 triangle ((90,",
"359.999... to 0, compare sin and cos of ang_A and ang_C: procExpected =",
"correct. Note that the sum ang_A + ang_C is 180, which is also",
"(90.0, 0.0, 90.0, True) else: expRes = (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa,",
"ang_C))) testData += [ # 90/90/90 triangle ((90, 90, 90), (90, 90, 90)),",
"< 0: ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C)))",
"a: expect A = 90, b = 0, C = 90, unknown #",
"- side_cc) % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif",
"value of side_bb is correct to within epsilon. - all relations are modulo",
"print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa",
"side_cc), expRes)) # a ~ 180, B = various, c various: # if",
"c - a, C = 0 # if c >> a: expect A",
"360) and side_aa ~= side_cc (modulo 360); cannot compute ang_A or ang_C: return",
"180 instead of 0. Bug fix: in some cases side_bb may be 180",
"if side_aa < EpsTest: expRes = (90.0, 180.0, 90.0, True) elif 180.0 -",
"side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute (a +/- c) / 2, and",
"-1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1],",
"numerator and denominator for analogy for bb - aa num3 = sin_h_cc *",
"suspect if side_bb < 0: side_bb = - side_bb if ang_A < 0:",
"180 side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa 180 where: - !pole means",
"# c ~ 0, B = various, a various: # if a nearly",
"in (180.0 - Eps, 180.0, 180.0 + Eps): for ang_B in (0.0, Eps,",
"various, c various: # if c nearly 180 (modulo 360): expect C =",
"0.5) sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B",
"side_cc ang_C = 0.0 else: ang_A = 0.0 side_bb = side_cc - side_aa",
"a nearly 180: expect C = 90, b = 180, A = 90,",
"cos_h_B * cos_h_A + sin_h_B * sin_h_A # numerator and denominator for analogy",
"Eps, 180.0, 180.0 + Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0,",
"360.0): for side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if",
"(modulo 360) and side_aa ~= side_cc (modulo 360); cannot compute ang_A or ang_C:",
"0.0, 90.0, True) elif abs((side_cc - 180) % 360.0) < EpsTest: expRes =",
"expRes)) # a fairly small but >> Eps, B varies, c = 90",
"179.0): for side_cc in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa),",
"# use Napier's analogy for bb - aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d",
"180 (modulo 360) - unknown(90) means unknownAng is set True and the angle",
"= various, a various: # if a nearly 0 (modulo 360): expect C",
"# with some tweaks to handle the other quadrants ang_B = 90.0 for",
"- sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B * sin_h_A",
"side_cc), expRes)) # B small, a = any not small, c = any",
"unknown(90) 0 unknown(90) any ~0 <side_aa 180 side_aa-cc 0 any ~0 >side_aa 0",
"0 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: #",
"0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc =",
"= sin_h_B * cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A",
"- the input argument # - the expected result: ang_C, side_bb, ang_A, [unknownAng]",
"= 180 - B for side_aa in (-Eps, 0.0, Eps): for ang_B in",
"these tweaks handle other quadrants; they're based on what works, so are somewhat",
"0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337,",
"(den3) > abs (num4) + abs (den4): # use Napier's analogy for bb",
"any not small: # if c != a: expect A = 90, b",
"somewhat suspect if side_bb < 0: side_bb = - side_bb if ang_A <",
"various: # if c nearly 0 (modulo 360): expect C = 90, b",
"180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_aa in (180.0, 180.0",
"nearly zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0",
"< opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360) and side_aa ~= side_cc (modulo",
"the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B",
"20.0, 45.0, 90, 110.0, 179.0): for side_cc in (1.0, 20.0, 45.0, 90.0, 110.0,",
"89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)),",
"a tuple containing: - ang_A angle a - side_bb side bb - ang_C",
"ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo 360) if",
"= 90.0 for side_aa in (1.0, 20.0, 45.0, 90, 110.0, 179.0): for side_cc",
"47.0, Eps, 0.0): if abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 0.0,",
"90, b = 0, A = 90, unknownAng # if a nearly 180:",
"# right triangle: B = 90, a and c vary but avoid poles",
"(den4): # use Napier's analogy for bb - aa side_bb = 2.0 *",
"- c, C = 180 for side_aa in (179.9, -27.0, 27.0, 0.1): for",
"outputVec[3], ) for testInput, expectedOutput in testData: if len(expectedOutput) < 4: expectedOutput =",
"code and unit test had errors 2011-01-28 ROwen Bug fix: unknownAng should always",
"various, a various: # if a nearly 0 (modulo 360): expect C =",
"\"unknownAng\" = true, ang_A = ang_C = 90.0. Also side_bb = 0.0, which",
"angles: [0, 360) - side_cc side cc Returns a tuple containing: - ang_A",
"360.0: print(\"failed on input:\", testInput) print(\"one or more angles out of range:\", actualOutput)",
"sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2, den2 =\", num1, den1,",
"nearly 180 (modulo 360): expect C = 90, b = 180, A =",
"90, 90)), # inputs that might cause side_bb < 0, (but should not)",
"(num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B =\", sin_h_B,",
"= opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import",
"* 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if",
"360.0): for side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if",
"0 or 180 Error Conditions: - If the inputs are too small to",
"2) = num/den num1 = cos_h_B * cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc",
"C = 90, b = 0, A = 90, unknownAng # if a",
"not small, c = any not small: # if c != a: expect",
"side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute (a +/- c) /",
"cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc,",
"- ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 180, B",
"ang_A and ang_C is correct and the value of side_bb is correct to",
"= opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa *",
"# if numerator and denominator are too small # to accurately determine angle",
"= 180, b = 180 - c, C = B for side_cc in",
"analogy for bb + aa num4 = sin_h_cc * cos_h_diff_BA den4 = cos_h_cc",
"C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute (a +/-",
"2) sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa",
"* opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly small but >>",
"side_aa side aa; range of sides: [0, 180] - ang_B angle b; range",
"= cos_h_B * cos_h_A + sin_h_B * sin_h_A # numerator and denominator for",
"360.0 - Eps, 360.0): for side_aa in (180.0, 180.0 - Eps, 179.0, 47.0,",
"# if c nearly 0 (modulo 360): expect C = 90, b =",
"* sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B * sin_h_A # numerator",
"from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb to unknownAng; side_bb may",
"compute sin((aa +/- cc) / 2) and cos((aa +/- cc) / 2) sin_h_sum_aacc",
"180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 0, B",
"180, b = 180 - c, C = B for side_cc in (180.0",
"= (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc),",
"= B for side_cc in (180.0 - Eps, 180.0): for ang_B in (0.0,",
"# - # compute sin((aa +/- cc) / 2) and cos((aa +/- cc)",
"* sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc =",
"% 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes =",
"den1, num2, den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC",
"angSideAng(*testInput) # to handle angles comparing things like 359.999... to 0, compare sin",
"a: expect A = 0, b = a - c, C = 180",
"side_cc ang_C = 180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is",
"print() if actualOutput[0] < 0.0 or actualOutput[0] >= 360.0 \\ or actualOutput[1] <",
"# + # compute side bb using one of two Napier's analogies #",
"for bb - aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa",
"processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput)",
"= 180.0 else: # + # compute angles a and c using Napier's",
"= c + a cos(B), A ~= 0 side_cc = 90.0 for side_aa",
"180: expect C = 90, b = 180, A = 90, unknownAng #",
"unknownAng is set True and the angle is unknown and is abitrarily set",
"* cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa",
"not nearly 0 or 360, c fairly small but >> Eps # expect:",
"# if c << a: expect A = 180, b = c -",
"~0 unknown(90) 180 unknown(90) ~180 any ~180 unknown(90) 0 unknown(90) ~180 any !pole",
"unknown(90) 0 unknown(90) ~180 any !pole 180 180-side_cc ang_B !pole any ~0 180-ang_B",
"b = 180, A = 90, unknownAng # else: expect A = 180,",
"elif abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else:",
"(180.0, side_aa - side_cc, 0.0) else: expRes = (0.0, side_cc - side_aa, 180.0)",
"C = 90, b = 180, A = 90, unknownAng # if a",
"computation, raises ValueError - If side bb is near 0 or 180 (see",
"sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B *",
"the other quadrants ang_B = 90.0 for side_aa in (1.0, 20.0, 45.0, 90,",
"mis-handled two cases: - side_aa tiny + side_cc normal: special case table, code",
"b = 180 - c, C = B for side_cc in (180.0 -",
"small but >> Eps, B varies, c = 90 # expect: C =",
"sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc #",
"* cos_h_A + sin_h_B * sin_h_A # numerator and denominator for analogy for",
"side_cc is nearly 180 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc)",
"= ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo 360)",
"= any not small, c = any not small: # if c !=",
"expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to False) # a ~",
"side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"errors 2011-01-28 ROwen Bug fix: unknownAng should always be true if side_aa and",
"90.0, True) else: # side_cc is not nearly 0 or 180 (modulo 360)",
"180.0 - Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for",
"# preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA",
"expRes = (90.0, 0.0, 90.0, True) elif abs((side_cc - 180) % 360.0) <",
"* sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA # numerator and denominator for analogy",
"C = B for side_cc in (180.0 - Eps, 180.0): for ang_B in",
"True) else: # side_cc is not nearly 0 or 180 (modulo 360) ang_A",
"ang_C = 90.0. Also side_bb = 0.0, which is essentially correct. Note that",
"to accurately determine angle = atan2 (num, den), give up if (((abs (num1)",
"2011-01-28 ROwen Bug fix: unknownAng should always be true if side_aa and side_cc",
"special cases after side_aa and side_cc special cases. Tweaked the documentation to clarify",
"or 180 (see Special Cases below for when this occurs) then angles a",
"180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0 - side_cc) % 360.0)",
"= 0, A = 90, unknownAng # if c nearly 180 (modulo 360):",
"opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B * cos_h_A",
"(0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps,",
"True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return",
"unit test were incorrect - side_aa normal + side_cc tiny: table was right",
"right triangle: B = 90, a and c vary but avoid poles #",
"two cases: - side_aa tiny + side_cc normal: special case table, code and",
"c ~ 180, B = various, a various: # if a nearly 0",
"Conditions: - If the inputs are too small to allow computation, raises ValueError",
"= 0.0 else: ang_A = 0.0 side_bb = side_cc - side_aa ang_C =",
"= sin_h_B * cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A",
"else: expRes = (0.0, side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc),",
"360, c fairly small but >> Eps # expect: A = 180 -",
"ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10,",
"Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa % 360.0) < EpsTest: expRes =",
"cannot compute ang_A or ang_C: return (90.0, 0.0, 90.0, True) elif side_cc <",
"cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B *",
"(num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A",
"+ aa num4 = sin_h_cc * cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA #",
"ang_B = 90.0 for side_aa in (1.0, 20.0, 45.0, 90, 110.0, 179.0): for",
"Standard Math Tables, crc, 15th ed, 1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen",
"90, b = 0, A = 90, unknownAng # else: expect A =",
"= cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc # compute numerator and denominator,",
"Selby, Standard Math Tables, crc, 15th ed, 1967, p161 (Spherical Trig.) History: 2002-07-22",
"# side_cc is nearly 180 (modulo 360) return (90.0, 0.0, 90.0, True) elif",
"but >> Eps, B varies, c = 90 # expect: C = 180",
"# side_aa is nearly 180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc",
"For example ~0 means approximately zero, 360, etc. Warnings: Allowing angles in the",
"abs((180.0 - side_cc) % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True)",
"print(\"failed on input:\", testInput) print(\"one or more angles out of range:\", actualOutput) print()",
"evaluating ang_B special cases after side_aa and side_cc special cases. Tweaked the documentation",
"b = 180, A = 90, unknownAng # else: expect A = 180",
"* 1.001 testData = [] # test data is formatted as follows: #",
"cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc # if",
"a - c, C = 180 for side_aa in (179.9, -27.0, 27.0, 0.1):",
"45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb",
"= (90.0, 180.0, 90.0, True) elif 180.0 - side_aa < EpsTest: expRes =",
"(0.0, side_cc - side_aa, 180.0) for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B,",
"180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData += [ #",
"= B for side_aa in (180.0 - Eps, 180.0, 180.0 + Eps): for",
"of two Napier's analogies # (one is for bb - aa, one for",
"num4 = sin_h_cc * cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA # compute side",
"expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0 - ang_B, side_aa,",
"ang_A = ang_B side_bb = 180.0 - side_aa ang_C = 180.0 elif abs(sin_h_B)",
"for bb - aa, one for bb + aa) # - # preliminaries",
"relations are modulo 360. For example ~0 means approximately zero, 360, etc. Warnings:",
"180 any ~0 ~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa 180 side_aa-cc 0",
"expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0] < 0.0 or actualOutput[0] >= 360.0",
"opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants; they're based on what works, so",
"ang_B, side_cc), expRes)) # a ~ 180, B = various, c various: #",
"- side_aa) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else:",
"180.0 - ang_B side_bb = side_aa ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy:",
"opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants;",
"clarify the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B =",
"B is nearly 0 (modulo 360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: #",
"b = 180, A = 90, unknownAng # if a nearly 180 (modulo",
"180 (modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc is not",
">> a: expect A = 0, b = a - c, C =",
"ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90) ~0 any ~180",
"both set to 90); bb will be 0 or 180 Error Conditions: -",
"if a nearly 180 (modulo 360): expect C = 90, b = 0,",
"abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo 360) and side_aa is",
"ang_B, side_cc), expRes)) # c ~ 0, B = various, a various: #",
"too small # to accurately determine angle = atan2 (num, den), give up",
"180 for side_aa in (179.9, -27.0, 27.0, 0.1): for side_cc in (side_aa -",
"b = a, C = 0 for side_cc in (0.0, Eps): for ang_B",
"angles in the 3rd and 4th quadrants is unusual. References: Selby, Standard Math",
"cases after side_aa and side_cc special cases. Tweaked the documentation to clarify the",
"/ 2, and use to compute angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d",
"various: # if a nearly 0: expect C = 90, b = 0,",
"side_aa in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 - Eps, 180,",
"angle a - side_bb side bb - ang_C angle c - unknownAng if",
"a ~ 0, B = various, c various: # if c nearly 0",
"example ~0 means approximately zero, 360, etc. Warnings: Allowing angles in the 3rd",
"= a + c cos(B), C ~= 0 side_aa = 90.0 for side_cc",
"b = a - c, C = 180 - B for side_aa in",
"a, C = 0 # if c >> a: expect A = 0,",
"= 90.0 for side_aa in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180",
"90)), # inputs that might cause side_bb < 0, (but should not) ((45,",
"and ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10):",
"expRes = (180.0, side_aa - side_cc, 0.0) else: expRes = (0.0, side_cc -",
"ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData +=",
"* sin_h_A # numerator and denominator for analogy for bb - aa num3",
"output:\", actualOutput) print() if actualOutput[0] < 0.0 or actualOutput[0] >= 360.0 \\ or",
"45.0, 90, 110.0, 179.0): for side_cc in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0):",
"num1 = cos_h_B * cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2 = cos_h_B",
"B = various, a various: # if a nearly 0 (modulo 360): expect",
"side_cc - side_aa, 180.0) for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc),",
"triangle for two angles and the side connecting them, given the remaining quantities.",
"are nearly 0 or 180 but that was not happening if ang_B was",
"* sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc =",
"opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa,",
"~= side_cc (modulo 360); cannot compute ang_A or ang_C: return (90.0, 0.0, 90.0,",
"a # tan c = (tan a / sinA * sinb) # with",
"b = 180 - c, C = B for side_aa in (180.0 -",
"angles a and c using Napier's analogies # - # compute sin((aa +/-",
"Eps, 179.0, 47.0, Eps, 0.0): if side_aa < EpsTest: expRes = (90.0, 180.0,",
"angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2,",
"should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337,",
"360.0 \\ or actualOutput[2] < 0.0 or actualOutput[2] >= 360.0: print(\"failed on input:\",",
"(num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy)",
"degrees. The sum of ang_A and ang_C is correct and the value of",
"Eps, 210.0, 360.0 - Eps, 360.0): for side_aa in (180.0, 180.0 - Eps,",
"(180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa % 360.0) <",
"triangle: B = 90, a and c vary but avoid poles # tan",
"small: # if c != a: expect A = 90, b = 0,",
"90.0, True) else: # side_cc is not nearly 0 or 180 ang_A =",
"sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA # numerator and denominator for analogy for",
"print(\"actual output:\", actualOutput) print() if actualOutput[0] < 0.0 or actualOutput[0] >= 360.0 \\",
"right but code and unit test had errors 2011-01-28 ROwen Bug fix: unknownAng",
"opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants; they're based on",
"use to compute angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC",
"set to 90 degrees. The sum of ang_A and ang_C is correct and",
"cc) / 2) and cos((aa +/- cc) / 2) sin_h_sum_aacc = sin_h_aa *",
"90.0 for side_aa in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 -",
"unit tests now pass. Greatly expanded the unit tests. 2010-08-04 ROwen Bug fix:",
"(num, den), give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <=",
"the input argument # - the expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng",
"nearly 0 or 180 ang_A = 0.0 side_bb = side_cc ang_C = 180.0",
"= 180 - B, b = a + c cos(B), C ~= 0",
"nearly 0 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy:",
"expRes)) # B small, a = any not small, c = any not",
"a / sinA * sinb) # with some tweaks to handle the other",
"= 180.0 side_bb = 180.0 - side_cc ang_C = ang_B elif abs(sin_h_cc) <",
"a and c cannot be computed. In this case \"unknownAng\" = true, ang_A",
"\"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest = Eps * 1.001",
"* sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc # compute",
">> Eps # expect: A = 180 - B, b = a +",
"+ # compute side bb using one of two Napier's analogies # (one",
"in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa % 360.0)",
"~= 0 side_cc = 90.0 for side_aa in (1.0e-12, 1.0e-10): for ang_B in",
"c nearly 0 (modulo 360): expect C = 90, b = 180, A",
"cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2 =",
"= 90, unknown # if c << a: expect A = 180, b",
"# inputs that might cause side_bb < 0, (but should not) ((45, 1,",
"the expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to False) # a",
"360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360)",
"in the 3rd and 4th quadrants is unusual. References: Selby, Standard Math Tables,",
"connecting them, given the remaining quantities. Inputs: - side_aa side aa; range of",
"rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print()",
"(0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0, 180.0 + Eps, 210.0,",
"side_cc is nearly 180 (modulo 360) and side_aa is not ang_A = ang_B",
"360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0",
"a = any not small, c = any not small: # if c",
"side_bb = 0.0, which is essentially correct. Note that the sum ang_A +",
"True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return",
"using one of two Napier's analogies # (one is for bb - aa,",
"= 180, A = 90, unknownAng # else: expect A = 180 -",
"can't compute ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc))",
"(modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360)",
"in (0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 -",
"+ Eps, 256, 359): expRes = (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0",
"# print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C",
"this case \"unknownAng\" = true, ang_A = ang_C = 90.0. Also side_bb =",
"the side connecting them, given the remaining quantities. Inputs: - side_aa side aa;",
"expRes)) # a = 90, B varies but not nearly 0 or 360,",
"if c nearly 0 (modulo 360): expect C = 90, b = 0,",
"correct. Special Cases (in the order they are handled): side_aa ang_B side_cc ang_A",
"EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0, 180.0 -",
"(90.0, 180.0, 90.0, True) else: expRes = (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa,",
"side cc Returns a tuple containing: - ang_A angle a - side_bb side",
"\"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2, den2 =\", num1,",
"unknown(90) ~0 any ~180 unknown(90) 180 unknown(90) ~0 any !pole 0 side_cc 180-ang_B",
"side_cc is nearly 180 (modulo 360) return (90.0, 180.0, 90.0, True) else: #",
"side_bb is correct to within epsilon. - all relations are modulo 360. For",
"bb if abs (num3) + abs (den3) > abs (num4) + abs (den4):",
"for side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc",
"expectedOutput in testData: if len(expectedOutput) < 4: expectedOutput = expectedOutput + (False,) actualOutput",
"True) else: expRes = (0.0, side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B,",
"= 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo 360)",
"+ cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B * sin_h_A",
"sin_h_cc # compute numerator and denominator, where tan((a +/- c) / 2) =",
"= 90, a and c vary but avoid poles # tan C =",
"Eps = 1.0e-15 EpsTest = Eps * 1.001 testData = [] # test",
"(modulo 360) ang_A = 180.0 side_bb = 180.0 - side_cc ang_C = ang_B",
"In this case \"unknownAng\" = true, ang_A = ang_C = 90.0. Also side_bb",
"0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle: B = 90, a",
"nearly 0 or 180 but that was not happening if ang_B was nearly",
"(90.0, 0.0, 90.0, True) elif abs((side_cc - 180) % 360.0) < EpsTest: expRes",
"ang_C = 0.0 else: ang_A = 0.0 side_bb = side_cc - side_aa ang_C",
"=\", h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C = h_sum_AC - h_diff_AC",
"C = 180 for side_aa in (179.9, -27.0, 27.0, 0.1): for side_cc in",
"90.0 for side_cc in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 -",
"Bug fix: unknownAng should always be true if side_aa and side_cc are nearly",
"~0 180-ang_B side_aa 0 !pole any ~180 ang_B 180-side_aa 180 any ~0 ~=side_aa",
"ang_B was nearly 0. Fixed by evaluating ang_B special cases after side_aa and",
"180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_aa in (180.0,",
"] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 0, B = various, a various:",
"~0 >side_aa 0 side_cc-aa 180 where: - !pole means not nearly 0 and",
"if side_bb < 0: side_bb = - side_bb if ang_A < 0: ang_A",
"unknown(90) ~180 any !pole 180 180-side_cc ang_B !pole any ~0 180-ang_B side_aa 0",
"side_bb, ang_A, [unknownAng] (unknownAng defaults to False) # a ~ 0, B =",
"+ Eps, side_aa + 45.0): if abs(side_cc - side_aa) < EpsTest: expRes =",
"opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other",
"(den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and C with side_aa=%s, ang_B=%s,",
"c various: # if c nearly 180 (modulo 360): expect C = 90,",
"side_cc): \"\"\" Solves a spherical triangle for two angles and the side connecting",
"handle the other quadrants ang_B = 90.0 for side_aa in (1.0, 20.0, 45.0,",
"If side bb is near 0 or 180 (see Special Cases below for",
"cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc",
"give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or",
"< opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo 360) if abs(side_aa - side_cc)",
"tiny + side_cc normal: special case table, code and unit test were incorrect",
"for analogy for bb + aa num4 = sin_h_cc * cos_h_diff_BA den4 =",
"abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0, 0.0,",
"[ # 90/90/90 triangle ((90, 90, 90), (90, 90, 90)), # inputs that",
"if len(expectedOutput) < 4: expectedOutput = expectedOutput + (False,) actualOutput = angSideAng(*testInput) #",
"359): expRes = (180.0 - ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa,",
"side_cc in (0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0",
"% (side_aa, ang_B, side_cc)) # compute (a +/- c) / 2, and use",
"bb - ang_C angle c - unknownAng if true, angle A and angle",
"(tan a / sinA * sinb) # with some tweaks to handle the",
"elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo 360) if abs(side_aa",
"like 359.999... to 0, compare sin and cos of ang_A and ang_C: procExpected",
"# compute sin((aa +/- cc) / 2) and cos((aa +/- cc) / 2)",
"zero (modulo 360) and side_aa is not ang_A = 180.0 - ang_B side_bb",
"Napier's analogies # - # compute sin((aa +/- cc) / 2) and cos((aa",
"in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C =",
"(modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360)",
"a ~ 180, B = various, c various: # if c nearly 180",
"opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5)",
"180.0 - Eps, 179.0, 47.0, Eps, 0.0): if side_aa < EpsTest: expRes =",
"opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs",
"# print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc",
"elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo 360) if abs(cos_h_cc)",
"A = 90, unknownAng # if a nearly 180 (modulo 360): expect C",
"A = 180, b = 180 - c, C = B for side_cc",
"C could not be computed (and are both set to 90); bb will",
"= a, C = 0 for side_cc in (0.0, Eps): for ang_B in",
"A = 90, unknownAng # if c nearly 0 (modulo 360): expect C",
"ang_C = h_sum_AC - h_diff_AC # + # compute side bb using one",
"0, A = 90, unknownAng # if c nearly 0 (modulo 360): expect",
"return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in",
"# compute side bb using one of two Napier's analogies # (one is",
"135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]),",
"\"\"\" Solves a spherical triangle for two angles and the side connecting them,",
"Eps, 210.0, 360.0 - Eps, 360.0): for side_cc in (180.0, 180.0 - Eps,",
"abs((side_cc - 180) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True)",
"180, A = 90, unknownAng # if a nearly 180 (modulo 360): expect",
"and c using Napier's analogies # - # compute sin((aa +/- cc) /",
"= true, ang_A = ang_C = 90.0. Also side_bb = 0.0, which is",
"- side_cc ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly",
"side bb if abs (num3) + abs (den3) > abs (num4) + abs",
"b; range of angles: [0, 360) - side_cc side cc Returns a tuple",
"b = c + a cos(B), A ~= 0 side_cc = 90.0 for",
"+ Eps, 210.0, 360.0 - Eps, 360.0): for side_aa in (180.0, 180.0 -",
"might cause side_bb < 0, (but should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337,",
"sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc -",
"cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly",
"90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]),",
"= ang_C = 90.0. Also side_bb = 0.0, which is essentially correct. Note",
"expRes)) # c ~ 180, B = various, a various: # if a",
"if c != a: expect A = 90, b = 0, C =",
"cc) / 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc",
"opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest = Eps * 1.001 testData =",
"ang_A = 180.0 side_bb = 180.0 - side_cc ang_C = ang_B elif abs(sin_h_cc)",
"< EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((side_cc - 180) %",
"with some tweaks to handle the other quadrants ang_B = 90.0 for side_aa",
"- side_cc, 0.0) else: expRes = (0.0, side_cc - side_aa, 180.0) for ang_B",
"else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos",
"(ang_A, side_bb, ang_C))) testData += [ # 90/90/90 triangle ((90, 90, 90), (90,",
"compute ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) #",
"360) return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is",
"actualOutput = angSideAng(*testInput) # to handle angles comparing things like 359.999... to 0,",
"inputs that might cause side_bb < 0, (but should not) ((45, 1, 45),",
"means unknownAng is set True and the angle is unknown and is abitrarily",
"ang_B, side_cc): \"\"\" Solves a spherical triangle for two angles and the side",
"tan C = tan c / sin a # tan c = (tan",
"unusual. References: Selby, Standard Math Tables, crc, 15th ed, 1967, p161 (Spherical Trig.)",
"opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360) and side_aa ~= side_cc (modulo 360);",
"!= a: expect A = 90, b = 0, C = 90, unknown",
"cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa",
"compute (a +/- c) / 2, and use to compute angles a and",
"table was right but code and unit test had errors 2011-01-28 ROwen Bug",
"1.0e-15 EpsTest = Eps * 1.001 testData = [] # test data is",
"sin_h_cc * cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA # compute side bb if",
"* sinb) # with some tweaks to handle the other quadrants ang_B =",
"Cases below for when this occurs) then angles a and c cannot be",
"+ (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B",
"(179.9, -27.0, 27.0, 0.1): for side_cc in (side_aa - 45.0, side_aa - Eps,",
"0, (but should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45),",
"# numerator and denominator for analogy for bb + aa num4 = sin_h_cc",
"abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((side_cc",
"210.0, 360.0 - Eps, 360.0): for side_aa in (180.0, 180.0 - Eps, 179.0,",
"angle is unknown and is abitrarily set to 90 degrees. The sum of",
"(180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 180,",
"Eps, 256, 359): expRes = (180.0 - ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)),",
"side_bb = side_aa - side_cc ang_C = 0.0 else: ang_A = 0.0 side_bb",
"side_aa = 90.0 for side_cc in (1.0e-12, 1.0e-10): for ang_B in (23, 90,",
"20.0, 45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa))",
"things like 359.999... to 0, compare sin and cos of ang_A and ang_C:",
"= 0.0, which is essentially correct. Note that the sum ang_A + ang_C",
"1-6. 2010-07-30 ROwen Changed output zero_bb to unknownAng; side_bb may be 180 instead",
"90, unknownAng # if c nearly 0 (modulo 360): expect C = 90,",
"side_aa: expRes = (180.0, side_aa - side_cc, 0.0) else: expRes = (0.0, side_cc",
"is nearly 180 (modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc",
"180.0, 180.0 + Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0",
"Special Cases (in the order they are handled): side_aa ang_B side_cc ang_A side_bb",
"python __all__ = [\"angSideAng\"] import opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\"",
"= 180, A = 90, unknownAng # if a nearly 180 (modulo 360):",
"True) elif abs((180.0 - side_aa) % 360.0) < EpsTest: expRes = (90.0, 180.0,",
"is nearly 180 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc) <",
"0 side_cc = 90.0 for side_aa in (1.0e-12, 1.0e-10): for ang_B in (23,",
"EpsTest: expRes = (90.0, 180.0, 90.0, True) elif 180.0 - side_aa < EpsTest:",
"abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo 360) if abs(side_aa -",
"also essentially correct. Special Cases (in the order they are handled): side_aa ang_B",
"bb + aa) # - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A",
"opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5)",
"and angle C could not be computed (and are both set to 90);",
"expectedOutput = expectedOutput + (False,) actualOutput = angSideAng(*testInput) # to handle angles comparing",
"import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical triangle for two",
"side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly",
"to handle the other quadrants ang_B = 90.0 for side_aa in (1.0, 20.0,",
"= cos_h_cc * cos_h_sum_BA # compute side bb if abs (num3) + abs",
"the order they are handled): side_aa ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0",
"num3 = sin_h_cc * sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA # numerator and",
"= 90, unknownAng # if c nearly 180 (modulo 360): expect C =",
"in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc % 360.0)",
"are modulo 360. For example ~0 means approximately zero, 360, etc. Warnings: Allowing",
"cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1,",
"processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput)",
"of ang_A and ang_C is correct and the value of side_bb is correct",
"abs((180.0 - side_aa) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True)",
"EpsTest: expRes = (90.0, 0.0, 90.0, True) else: expRes = (ang_B, 180.0 -",
"b = 0, A = 90, unknownAng # if c nearly 180 (modulo",
"a: expect A = 180, b = c - a, C = 0",
"cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B * sin_h_A # numerator and denominator",
"expRes = (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a",
"ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) *",
"(one is for bb - aa, one for bb + aa) # -",
"comparing things like 359.999... to 0, compare sin and cos of ang_A and",
"bb is near 0 or 180 (see Special Cases below for when this",
"\"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print",
"= 90, unknownAng # else: expect A = 180 - B, b =",
"for ang_B in (23, 90, 180 - Eps, 180, 180 + Eps, 256,",
"actualOutput[1] >= 360.0 \\ or actualOutput[2] < 0.0 or actualOutput[2] >= 360.0: print(\"failed",
"side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb =",
"- Eps, 180.0): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 -",
"0, A = 90, unknownAng # if a nearly 180: expect C =",
"Inputs: - side_aa side aa; range of sides: [0, 180] - ang_B angle",
"may be 180 and ang_A and ang_C unknown. Improved accuracy in some corner",
"but >> Eps # expect: A = 180 - B, b = a",
"side_cc < side_aa: ang_A = 180.0 side_bb = side_aa - side_cc ang_C =",
"b = a + c cos(B), C ~= 0 side_aa = 90.0 for",
"C = 90, unknown # if c << a: expect A = 180,",
"sin_h_sum_aacc # print \"num1, den1, num2, den2 =\", num1, den1, num2, den2 #",
"0.0): if abs(side_aa % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True)",
"# if c >> a: expect A = 0, b = a -",
"- !pole means not nearly 0 and not nearly 180 (modulo 360) -",
"(and are both set to 90); bb will be 0 or 180 Error",
"360, etc. Warnings: Allowing angles in the 3rd and 4th quadrants is unusual.",
"cannot be computed. In this case \"unknownAng\" = true, ang_A = ang_C =",
"and unit test were incorrect - side_aa normal + side_cc tiny: table was",
"= (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~",
"- c, C = B for side_cc in (180.0 - Eps, 180.0): for",
"360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return",
"sin_h_cc * sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA # numerator and denominator for",
"< EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0 -",
"with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute (a +/- c)",
"- If the inputs are too small to allow computation, raises ValueError -",
"unknownAng # else: expect A = 0, b = a - c, C",
"References: Selby, Standard Math Tables, crc, 15th ed, 1967, p161 (Spherical Trig.) History:",
"= side_cc - side_aa ang_C = 180.0 else: # + # compute angles",
"side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ ==",
"< EpsTest: expRes = (90.0, 0.0, 90.0, True) elif side_cc < side_aa: expRes",
"90, B varies but not nearly 0 or 360, c fairly small but",
"180-ang_B ~180 any ~0 unknown(90) 180 unknown(90) ~180 any ~180 unknown(90) 0 unknown(90)",
"Eps, 0.0): if abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0,",
"ang_A = ang_C = 90.0. Also side_bb = 0.0, which is essentially correct.",
"and the side connecting them, given the remaining quantities. Inputs: - side_aa side",
"and denominator are too small # to accurately determine angle = atan2 (num,",
"or 180 ang_A = 0.0 side_bb = side_cc ang_C = 180.0 - ang_B",
"= tan c / sin a # tan c = (tan a /",
"Eps, 256, 359): expRes = (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 -",
"side bb is near 0 or 180 (see Special Cases below for when",
"\"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B",
"180.0): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0,",
"= ang_B side_bb = 180.0 - side_aa ang_C = 180.0 elif abs(sin_h_B) <",
"\\ or actualOutput[2] < 0.0 or actualOutput[2] >= 360.0: print(\"failed on input:\", testInput)",
"(but should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066,",
"den), give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy))",
"0.0) else: expRes = (0.0, side_cc - side_aa, 180.0) for ang_B in (-Eps,",
"=\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2, den2 =\", num1, den1, num2,",
"expect A = 0, b = a - c, C = 180 -",
"Eps, 360.0): for side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0):",
"(modulo 360): expect C = 90, b = 180, A = 90, unknownAng",
"# compute numerator and denominator, where tan((a +/- c) / 2) = num/den",
"essentially correct. Special Cases (in the order they are handled): side_aa ang_B side_cc",
"sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc",
"- the expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to False) #",
"and side_aa is not ang_A = ang_B side_bb = 180.0 - side_aa ang_C",
"which is essentially correct. Note that the sum ang_A + ang_C is 180,",
"h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C = h_sum_AC -",
"any ~0 180-ang_B side_aa 0 !pole any ~180 ang_B 180-side_aa 180 any ~0",
"# if a nearly 180 (modulo 360): expect C = 90, b =",
"ang_A + ang_C is 180, which is also essentially correct. Special Cases (in",
"small to allow computation, raises ValueError - If side bb is near 0",
"(see Special Cases below for when this occurs) then angles a and c",
"- ang_C angle c - unknownAng if true, angle A and angle C",
"# side_cc is nearly 0 (modulo 360) return (90.0, 180.0, 90.0, True) else:",
"cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc",
"__name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest = Eps",
"angle = atan2 (num, den), give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and",
"procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected",
"incorrect - side_aa normal + side_cc tiny: table was right but code and",
"0 unknown(90) any ~0 <side_aa 180 side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa",
"side_aa in (1.0, 20.0, 45.0, 90, 110.0, 179.0): for side_cc in (1.0, 20.0,",
"Changed output zero_bb to unknownAng; side_bb may be 180 instead of 0. Bug",
"= 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return",
"((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135,",
"b = 0, A = 90, unknownAng # if c nearly 0 (modulo",
"ang_B special cases after side_aa and side_cc special cases. Tweaked the documentation to",
"(modulo 360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo",
"side_aa in (-Eps, 0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0,",
"which is also essentially correct. Special Cases (in the order they are handled):",
"happening if ang_B was nearly 0. Fixed by evaluating ang_B special cases after",
"if ang_C < 0: ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A,",
"[\"angSideAng\"] import opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical",
"side_aa - side_cc ang_C = 0.0 else: ang_A = 0.0 side_bb = side_cc",
"#!/usr/bin/env python __all__ = [\"angSideAng\"] import opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc):",
"for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle:",
"< EpsTest: expRes = (90.0, 0.0, 90.0, True) else: expRes = (ang_B, 180.0",
"ROwen Bug fix: mis-handled two cases: - side_aa tiny + side_cc normal: special",
"nearly 0 (modulo 360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~=",
"< 0: ang_A = 180.0 + ang_A if ang_C < 0: ang_C =",
"180 (modulo 360) and side_aa is not ang_A = ang_B side_bb = 180.0",
"= cos_h_B * cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2 = cos_h_B *",
"side_aa is not ang_A = 180.0 - ang_B side_bb = side_aa ang_C =",
"---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90) ~0 any ~180 unknown(90) 180 unknown(90)",
"correct and the value of side_bb is correct to within epsilon. - all",
"triangle ((90, 90, 90), (90, 90, 90)), # inputs that might cause side_bb",
"=\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc,",
"side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 180, B = various,",
"180 unknown(90) ~180 any ~180 unknown(90) 0 unknown(90) ~180 any !pole 180 180-side_cc",
"expRes = (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c",
">= 360.0 \\ or actualOutput[2] < 0.0 or actualOutput[2] >= 360.0: print(\"failed on",
"c >> a: expect A = 0, b = a - c, C",
"sinb) # with some tweaks to handle the other quadrants ang_B = 90.0",
"180.0, 90.0, True) elif 180.0 - side_aa < EpsTest: expRes = (90.0, 0.0,",
"ang_A and ang_C unknown. Improved accuracy in some corner cases; all unit tests",
"= (90.0, 0.0, 90.0, True) elif abs((side_cc - 180) % 360.0) < EpsTest:",
"ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B small, a = any not small,",
"raises ValueError - If side bb is near 0 or 180 (see Special",
"# side_cc is nearly 180 (modulo 360) return (90.0, 180.0, 90.0, True) else:",
"side_bb = side_cc - side_aa ang_C = 180.0 else: # + # compute",
"side_bb < 0: side_bb = - side_bb if ang_A < 0: ang_A =",
"c nearly 180 (modulo 360): expect C = 90, b = 0, A",
"nearly 0: expect C = 90, b = 0, A = 90, unknownAng",
"side_cc is not nearly 0 or 180 (modulo 360) ang_A = 180.0 side_bb",
"= opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy:",
"side_bb may be 180 and ang_A and ang_C unknown. Improved accuracy in some",
"ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to False) # a ~ 0, B",
"in (179.9, -27.0, 27.0, 0.1): for side_cc in (side_aa - 45.0, side_aa -",
"side_aa + 45.0): if abs(side_cc - side_aa) < EpsTest: expRes = (90.0, 0.0,",
"c = 90 # expect: C = 180 - B, b = c",
"side_bb if ang_A < 0: ang_A = 180.0 + ang_A if ang_C <",
"test had errors 2011-01-28 ROwen Bug fix: unknownAng should always be true if",
"~= 0 (modulo 360) and side_aa ~= side_cc (modulo 360); cannot compute ang_A",
"= 0, C = 90, unknown # if c << a: expect A",
"is not ang_A = ang_B side_bb = 180.0 - side_aa ang_C = 180.0",
"them, given the remaining quantities. Inputs: - side_aa side aa; range of sides:",
"are somewhat suspect if side_bb < 0: side_bb = - side_bb if ang_A",
"0: ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData",
"and c vary but avoid poles # tan C = tan c /",
"0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa =",
"opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) and side_aa is not ang_A",
"unknownAng # if a nearly 180 (modulo 360): expect C = 90, b",
"-1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1,",
"for side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa",
"(-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle: B = 90,",
"True) elif 180.0 - side_aa < EpsTest: expRes = (90.0, 0.0, 90.0, True)",
"by evaluating ang_B special cases after side_aa and side_cc special cases. Tweaked the",
"accuracy in some corner cases; all unit tests now pass. Greatly expanded the",
"side_aa: ang_A = 180.0 side_bb = side_aa - side_cc ang_C = 0.0 else:",
"bb - aa num3 = sin_h_cc * sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA",
"180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a = 90, B",
"opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5)",
"(90.0, 180.0, 90.0, True) elif 180.0 - side_aa < EpsTest: expRes = (90.0,",
"if side_aa and side_cc are nearly 0 or 180 but that was not",
"pass. Greatly expanded the unit tests. 2010-08-04 ROwen Bug fix: mis-handled two cases:",
"preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA =",
"using Napier's analogies # - # compute sin((aa +/- cc) / 2) and",
"abs(side_aa % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((180.0",
"= any not small: # if c != a: expect A = 90,",
"sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B",
"47.0, Eps, 0.0): if side_aa < EpsTest: expRes = (90.0, 180.0, 90.0, True)",
"= (180.0, side_aa - side_cc, 0.0) else: expRes = (0.0, side_cc - side_aa,",
"= 180.0 - side_cc ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc",
"= (90.0, 0.0, 90.0, True) else: expRes = (ang_B, 180.0 - side_aa, 180.0)",
"90.0, True) else: expRes = (0.0, side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa,",
"~0 means approximately zero, 360, etc. Warnings: Allowing angles in the 3rd and",
"ang_A < 0: ang_A = 180.0 + ang_A if ang_C < 0: ang_C",
"else: expect A = 180, b = 180 - c, C = B",
"90/90/90 triangle ((90, 90, 90), (90, 90, 90)), # inputs that might cause",
"180 - Eps, 180, 180 + Eps, 256, 359): expRes = (0.0, side_cc",
"fix: unknownAng should always be true if side_aa and side_cc are nearly 0",
"angles and the side connecting them, given the remaining quantities. Inputs: - side_aa",
"Bug fix: in some cases side_bb may be 180 and ang_A and ang_C",
"set True and the angle is unknown and is abitrarily set to 90",
"expect A = 180, b = 180 - c, C = B for",
"=\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc",
"expRes = (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c",
"and is abitrarily set to 90 degrees. The sum of ang_A and ang_C",
"(side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly small but",
"side_cc in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 - Eps, 180,",
"180.0 - side_aa < EpsTest: expRes = (90.0, 0.0, 90.0, True) else: expRes",
"180 ang_A = 0.0 side_bb = side_cc ang_C = 180.0 - ang_B elif",
"< EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0, 180.0",
"side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360) and side_aa ~= side_cc",
"output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0] < 0.0 or actualOutput[0] >=",
"side_aa, side_aa + Eps, side_aa + 45.0): if abs(side_cc - side_aa) < EpsTest:",
"nearly 0 (modulo 360): expect C = 90, b = 180, A =",
"90), (90, 90, 90)), # inputs that might cause side_bb < 0, (but",
"c) / 2, and use to compute angles a and c h_sum_AC =",
"opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these",
"c vary but avoid poles # tan C = tan c / sin",
"one for bb + aa) # - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A *",
"and ang_C unknown. Improved accuracy in some corner cases; all unit tests now",
"and side_cc are nearly 0 or 180 but that was not happening if",
"handle other quadrants; they're based on what works, so are somewhat suspect if",
"ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData += [ # 90/90/90 triangle",
"180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_cc in (180.0, 180.0",
"that might cause side_bb < 0, (but should not) ((45, 1, 45), (89.6464421219342,",
"0, B = various, c various: # if c nearly 0 (modulo 360):",
"b = a - c, C = 180 for side_aa in (179.9, -27.0,",
"in some corner cases; all unit tests now pass. Greatly expanded the unit",
"* sin_h_sum_aacc # if numerator and denominator are too small # to accurately",
"and side_aa ~= side_cc (modulo 360); cannot compute ang_A or ang_C: return (90.0,",
"abs (num3) + abs (den3) > abs (num4) + abs (den4): # use",
"side_bb = - side_bb if ang_A < 0: ang_A = 180.0 + ang_A",
"num2, den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC +",
"return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\")",
"210.0, 360.0 - Eps, 360.0): for side_cc in (180.0, 180.0 - Eps, 179.0,",
"abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0, 180.0,",
"side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90) ~0 any",
"c << a: expect A = 180, b = c - a, C",
"epsilon. - all relations are modulo 360. For example ~0 means approximately zero,",
"sin_h_sum_aacc # if numerator and denominator are too small # to accurately determine",
"90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb =",
"= various, c various: # if c nearly 0 (modulo 360): expect C",
"compute numerator and denominator, where tan((a +/- c) / 2) = num/den num1",
"~0 <side_aa 180 side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa 180 where: -",
"side_aa, 180.0) for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"ang_B side_bb = side_aa ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc",
"# to handle angles comparing things like 359.999... to 0, compare sin and",
"print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2, den2 =\",",
"a various: # if a nearly 0 (modulo 360): expect C = 90,",
"c ~ 0, B = various, a various: # if a nearly 0:",
"- ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly small but >> Eps, B varies,",
"# 90/90/90 triangle ((90, 90, 90), (90, 90, 90)), # inputs that might",
"+ c cos(B), C ~= 0 side_aa = 90.0 for side_cc in (1.0e-12,",
"but code and unit test had errors 2011-01-28 ROwen Bug fix: unknownAng should",
"in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0 - side_cc)",
"nearly 0 and not nearly 180 (modulo 360) - unknown(90) means unknownAng is",
"= 0.0 side_bb = side_cc ang_C = 180.0 - ang_B elif abs(cos_h_aa) <",
"ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed",
"+ Eps, 256, 359): expRes = (180.0 - ang_B, side_aa + (side_cc *",
"360.0 - Eps, 360.0): for side_cc in (180.0, 180.0 - Eps, 179.0, 47.0,",
"< EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs(side_cc % 360.0) <",
"opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: #",
"0.0 or actualOutput[1] >= 360.0 \\ or actualOutput[2] < 0.0 or actualOutput[2] >=",
"Eps, B varies, c = 90 # expect: C = 180 - B,",
"aa) # - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A",
"= 0, b = a - c, C = 180 - B for",
"if ang_B was nearly 0. Fixed by evaluating ang_B special cases after side_aa",
"sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc # compute numerator",
"ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo 360) and",
"cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B *",
"a - c, C = 180 - B for side_aa in (-Eps, 0.0,",
"- 180) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else:",
"0.0): if abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True)",
"bb using one of two Napier's analogies # (one is for bb -",
"# tan c = (tan a / sinA * sinb) # with some",
"is not nearly 0 or 180 (modulo 360) ang_A = 180.0 side_bb =",
"documentation to clarify the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc)",
"* cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa",
"180.0, 90.0, True) else: expRes = (0.0, side_cc - side_aa, 180.0 - ang_B)",
"A ~= 0 side_cc = 90.0 for side_aa in (1.0e-12, 1.0e-10): for ang_B",
"ang_B angle b; range of angles: [0, 360) - side_cc side cc Returns",
"Napier's analogies # (one is for bb - aa, one for bb +",
"ang_A or ang_C: return (90.0, 0.0, 90.0, True) elif side_cc < side_aa: ang_A",
"various: # if c nearly 180 (modulo 360): expect C = 90, b",
"print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C =",
"unknown(90) 0 unknown(90) ~0 any ~180 unknown(90) 180 unknown(90) ~0 any !pole 0",
"will be 0 or 180 Error Conditions: - If the inputs are too",
"abs (den3) > abs (num4) + abs (den4): # use Napier's analogy for",
"cos(B), A ~= 0 side_cc = 90.0 for side_aa in (1.0e-12, 1.0e-10): for",
"< side_aa: expRes = (180.0, side_aa - side_cc, 0.0) else: expRes = (0.0,",
"- side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 0, B =",
"fix: in some cases side_bb may be 180 and ang_A and ang_C unknown.",
"nearly 0 (modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc is",
"B varies, c = 90 # expect: C = 180 - B, b",
"h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B #",
"= 180, A = 90, unknownAng # else: expect A = 0, b",
"# - the input argument # - the expected result: ang_C, side_bb, ang_A,",
"c fairly small but >> Eps # expect: A = 180 - B,",
"256, 359): expRes = (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B)",
"(unknownAng defaults to False) # a ~ 0, B = various, c various:",
"(abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <=",
"0: expect C = 90, b = 0, A = 90, unknownAng #",
"- a, C = 0 # if c >> a: expect A =",
"any ~180 unknown(90) 180 unknown(90) ~0 any !pole 0 side_cc 180-ang_B ~180 any",
"= 180 - c, C = B for side_aa in (180.0 - Eps,",
"side_aa and side_cc are nearly 0 or 180 but that was not happening",
"0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 180, B = various, a",
"aa num3 = sin_h_cc * sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA # numerator",
") for testInput, expectedOutput in testData: if len(expectedOutput) < 4: expectedOutput = expectedOutput",
"+ aa) # - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A =",
"% 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((side_cc -",
"B = various, c various: # if c nearly 0 (modulo 360): expect",
"vary but avoid poles # tan C = tan c / sin a",
"0 side_cc 180-ang_B ~180 any ~0 unknown(90) 180 unknown(90) ~180 any ~180 unknown(90)",
"a, C = 0 for side_cc in (0.0, Eps): for ang_B in (0.0,",
"+ side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb",
"180 - Eps, 180, 180 + Eps, 256, 359): expRes = (180.0 -",
"return (90.0, 0.0, 90.0, True) elif side_cc < side_aa: ang_A = 180.0 side_bb",
"den2 = sin_h_B * sin_h_sum_aacc # if numerator and denominator are too small",
"0: side_bb = - side_bb if ang_A < 0: ang_A = 180.0 +",
"# + # compute angles a and c using Napier's analogies # -",
"= cos_h_cc * sin_h_sum_BA # numerator and denominator for analogy for bb +",
"sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc -",
"90, unknownAng # else: expect A = 180, b = 180 - c,",
"cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa *",
"opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo",
"abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360) and side_aa",
"Cases (in the order they are handled): side_aa ang_B side_cc ang_A side_bb ang_C",
"= expectedOutput + (False,) actualOutput = angSideAng(*testInput) # to handle angles comparing things",
"nearly 180 (modulo 360) and side_aa is not ang_A = ang_B side_bb =",
"data is formatted as follows: # a list of entries, each consisting of:",
"if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2)",
"opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo 360) and side_aa is not ang_A",
"angle A and angle C could not be computed (and are both set",
"# else: expect A = 180, b = 180 - c, C =",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 180, B = various, a various:",
"Allowing angles in the 3rd and 4th quadrants is unusual. References: Selby, Standard",
"= 90, b = 180, A = 90, unknownAng # if a nearly",
"360. For example ~0 means approximately zero, 360, etc. Warnings: Allowing angles in",
"EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((side_cc - 180) % 360.0)",
"sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc # if numerator and denominator are too",
"B, b = a, C = 0 for side_cc in (0.0, Eps): for",
"cos(B), C ~= 0 side_aa = 90.0 for side_cc in (1.0e-12, 1.0e-10): for",
"and unit test had errors 2011-01-28 ROwen Bug fix: unknownAng should always be",
"testData: if len(expectedOutput) < 4: expectedOutput = expectedOutput + (False,) actualOutput = angSideAng(*testInput)",
"ang_A angle a - side_bb side bb - ang_C angle c - unknownAng",
"180, B = various, a various: # if a nearly 0 (modulo 360):",
"for side_cc in (0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0,",
"2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A),",
"= 180 for side_aa in (179.9, -27.0, 27.0, 0.1): for side_cc in (side_aa",
"if ang_A < 0: ang_A = 180.0 + ang_A if ang_C < 0:",
"= sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc",
"input argument # - the expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults",
"A = 90, unknownAng # if a nearly 180: expect C = 90,",
"= (180.0 - ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc),",
"if abs(side_cc - side_aa) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif",
"= opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B",
"computed. In this case \"unknownAng\" = true, ang_A = ang_C = 90.0. Also",
"90, 180 - Eps, 180, 180 + Eps, 256, 359): expRes = (0.0,",
"= 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360)",
"Eps, 0.0): if abs((180.0 - side_cc) % 360.0) < EpsTest: expRes = (90.0,",
"sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\",",
"= (90.0, 0.0, 90.0, True) elif side_cc < side_aa: expRes = (180.0, side_aa",
"elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0,",
"in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0, 180.0 + Eps,",
"B small, a = any not small, c = any not small: #",
"EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((180.0 - side_aa) % 360.0)",
"Tables, crc, 15th ed, 1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted from",
"= 90, B varies but not nearly 0 or 360, c fairly small",
"= opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B",
"45.0, side_aa - Eps, side_aa, side_aa + Eps, side_aa + 45.0): if abs(side_cc",
"ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90) ~0 any ~180 unknown(90) 180",
"- c, C = 180 - B for side_aa in (-Eps, 0.0, Eps):",
"normal + side_cc tiny: table was right but code and unit test had",
"= 180.0 side_bb = side_aa - side_cc ang_C = 0.0 else: ang_A =",
"* cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc #",
"is set True and the angle is unknown and is abitrarily set to",
"(1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 - Eps, 180, 180 +",
"0.0, 90.0, True) elif side_cc < side_aa: ang_A = 180.0 side_bb = side_aa",
"actualOutput[0] < 0.0 or actualOutput[0] >= 360.0 \\ or actualOutput[1] < 0.0 or",
"quadrants is unusual. References: Selby, Standard Math Tables, crc, 15th ed, 1967, p161",
"opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) #",
"- unknown(90) means unknownAng is set True and the angle is unknown and",
"(side_aa - 45.0, side_aa - Eps, side_aa, side_aa + Eps, side_aa + 45.0):",
"(90, 90, 90)), # inputs that might cause side_bb < 0, (but should",
"opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical triangle for",
"and side_aa is not ang_A = 180.0 - ang_B side_bb = side_aa ang_C",
"- cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc",
"unknownAng; side_bb may be 180 instead of 0. Bug fix: in some cases",
"side_aa - side_cc, 0.0) else: expRes = (0.0, side_cc - side_aa, 180.0) for",
"0 or 180 but that was not happening if ang_B was nearly 0.",
"Trig.) History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output",
"a nearly 0: expect C = 90, b = 0, A = 90,",
"expect: A = 180 - B, b = a + c cos(B), C",
"179.0, 47.0, Eps, 0.0): if side_aa < EpsTest: expRes = (90.0, 180.0, 90.0,",
"if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360) and",
"sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) <",
"side_cc tiny: table was right but code and unit test had errors 2011-01-28",
"- Eps, 180, 180 + Eps, 256, 359): expRes = (180.0 - ang_B,",
"opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa =",
"else: # + # compute angles a and c using Napier's analogies #",
"= h_sum_AC + h_diff_AC ang_C = h_sum_AC - h_diff_AC # + # compute",
"for side_aa in (179.9, -27.0, 27.0, 0.1): for side_cc in (side_aa - 45.0,",
"crc, 15th ed, 1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted from TCC's",
"+ abs (den3) > abs (num4) + abs (den4): # use Napier's analogy",
"= sin_h_cc * sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA # numerator and denominator",
"p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen",
"cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc,",
"0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308,",
"and use to compute angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1)",
"is correct to within epsilon. - all relations are modulo 360. For example",
"180, B = various, c various: # if c nearly 180 (modulo 360):",
"cos((aa +/- cc) / 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa *",
"= [] # test data is formatted as follows: # a list of",
"abs(side_cc - side_aa) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif side_cc",
"sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B * sin_h_A #",
"# numerator and denominator for analogy for bb - aa num3 = sin_h_cc",
"<= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and",
"side_cc special cases. Tweaked the documentation to clarify the special cases. \"\"\" sin_h_aa",
"+ abs (den4): # use Napier's analogy for bb - aa side_bb =",
"cos of ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected,",
"or 180 Error Conditions: - If the inputs are too small to allow",
"for side_aa in (180.0 - Eps, 180.0, 180.0 + Eps): for ang_B in",
"ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute (a +/- c) / 2,",
"modulo 360. For example ~0 means approximately zero, 360, etc. Warnings: Allowing angles",
"- # compute sin((aa +/- cc) / 2) and cos((aa +/- cc) /",
"always be true if side_aa and side_cc are nearly 0 or 180 but",
"< opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy:",
"< opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) and side_aa is not",
"180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo",
"range of angles: [0, 360) - side_cc side cc Returns a tuple containing:",
"is nearly 0 (modulo 360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B",
"ang_A = 180.0 side_bb = side_aa - side_cc ang_C = 0.0 else: ang_A",
"ang_B in (23, 90, 180 - Eps, 180, 180 + Eps, 256, 359):",
"num1, den1, num2, den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A =",
"360); cannot compute ang_A or ang_C: return (90.0, 0.0, 90.0, True) elif side_cc",
"180, b = 180 - c, C = B for side_aa in (180.0",
"in (180.0 - Eps, 180.0): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0,",
"- Eps, side_aa, side_aa + Eps, side_aa + 45.0): if abs(side_cc - side_aa)",
"B = 90, a and c vary but avoid poles # tan C",
"c) / 2) = num/den num1 = cos_h_B * cos_h_diff_aacc den1 = sin_h_B",
"(modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc is not nearly",
"+ side_cc normal: special case table, code and unit test were incorrect -",
"~0 any ~0 unknown(90) 0 unknown(90) ~0 any ~180 unknown(90) 180 unknown(90) ~0",
"sum ang_A + ang_C is 180, which is also essentially correct. Special Cases",
"Eps, 180, 180 + Eps, 256, 359): expRes = (180.0 - ang_B, side_aa",
"len(expectedOutput) < 4: expectedOutput = expectedOutput + (False,) actualOutput = angSideAng(*testInput) # to",
"return (90.0, 180.0, 90.0, True) else: # side_cc is not nearly 0 or",
"< 0.0 or actualOutput[2] >= 360.0: print(\"failed on input:\", testInput) print(\"one or more",
"0 or 360, c fairly small but >> Eps # expect: A =",
"spherical triangle for two angles and the side connecting them, given the remaining",
"Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb to unknownAng; side_bb",
"0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa)",
"+ sin_h_aa * sin_h_cc # compute numerator and denominator, where tan((a +/- c)",
"ang_B ~= 0 (modulo 360) and side_aa ~= side_cc (modulo 360); cannot compute",
"180 - B, b = a + c cos(B), C ~= 0 side_aa",
"< 4: expectedOutput = expectedOutput + (False,) actualOutput = angSideAng(*testInput) # to handle",
"approximately zero, 360, etc. Warnings: Allowing angles in the 3rd and 4th quadrants",
"= opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B *",
"* sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc # if numerator and denominator are",
"expect A = 0, b = a - c, C = 180 for",
"!pole 180 180-side_cc ang_B !pole any ~0 180-ang_B side_aa 0 !pole any ~180",
"testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0] < 0.0 or",
"opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and C",
"- B, b = a + c cos(B), C ~= 0 side_aa =",
"expanded the unit tests. 2010-08-04 ROwen Bug fix: mis-handled two cases: - side_aa",
"are both set to 90); bb will be 0 or 180 Error Conditions:",
"= cos_h_B * cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A",
"180, A = 90, unknownAng # else: expect A = 0, b =",
"= 180 - c, C = B for side_cc in (180.0 - Eps,",
"actualOutput[2] < 0.0 or actualOutput[2] >= 360.0: print(\"failed on input:\", testInput) print(\"one or",
"in (1.0, 20.0, 45.0, 90, 110.0, 179.0): for side_cc in (1.0, 20.0, 45.0,",
"Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_aa in",
"quadrants; they're based on what works, so are somewhat suspect if side_bb <",
"- aa num3 = sin_h_cc * sin_h_diff_BA den3 = cos_h_cc * sin_h_sum_BA #",
"fairly small but >> Eps, B varies, c = 90 # expect: C",
"0 unknown(90) ~180 any !pole 180 180-side_cc ang_B !pole any ~0 180-ang_B side_aa",
"= 90.0 for side_cc in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180",
"[0, 360) - side_cc side cc Returns a tuple containing: - ang_A angle",
"Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0, 180.0 + Eps, 210.0, 360.0",
"180 but that was not happening if ang_B was nearly 0. Fixed by",
"180 - c, C = B for side_aa in (180.0 - Eps, 180.0,",
"* 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa",
"den2) # print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\",",
"C = 180 - B for side_aa in (-Eps, 0.0, Eps): for ang_B",
"c != a: expect A = 90, b = 0, C = 90,",
"B = various, a various: # if a nearly 0: expect C =",
"/ 2) and cos((aa +/- cc) / 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc",
"and ang_C is correct and the value of side_bb is correct to within",
"compute side bb if abs (num3) + abs (den3) > abs (num4) +",
"= 180.0 - ang_B side_bb = side_aa ang_C = 0.0 elif abs(cos_h_cc) <",
"<= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and",
"- aa, one for bb + aa) # - # preliminaries sin_h_A =",
"expect: C = 180 - B, b = c + a cos(B), A",
"a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2)",
"side_cc), expRes)) # a = 90, B varies but not nearly 0 or",
"various: # if a nearly 0 (modulo 360): expect C = 90, b",
"- Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc % 360.0) < EpsTest: expRes",
"any ~0 ~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa 180 side_aa-cc 0 any",
"is nearly 0 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc) <",
"= c - a, C = 0 # if c >> a: expect",
"0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B",
"expect C = 90, b = 180, A = 90, unknownAng # if",
"- side_aa side aa; range of sides: [0, 180] - ang_B angle b;",
"range of sides: [0, 180] - ang_B angle b; range of angles: [0,",
"cases; all unit tests now pass. Greatly expanded the unit tests. 2010-08-04 ROwen",
"c, C = B for side_aa in (180.0 - Eps, 180.0, 180.0 +",
"numerator and denominator, where tan((a +/- c) / 2) = num/den num1 =",
"# a fairly small but >> Eps, B varies, c = 90 #",
"true if side_aa and side_cc are nearly 0 or 180 but that was",
"ang_A = 180.0 - ang_B side_bb = side_aa ang_C = 0.0 elif abs(cos_h_cc)",
"for side_aa in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 - Eps,",
"0.0 else: ang_A = 0.0 side_bb = side_cc - side_aa ang_C = 180.0",
"180.0 - side_cc ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is",
"ang_B, side_cc), (ang_A, side_bb, ang_C))) testData += [ # 90/90/90 triangle ((90, 90,",
"= - side_bb if ang_A < 0: ang_A = 180.0 + ang_A if",
"+/- cc) / 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc",
"not nearly 0 or 180 ang_A = 0.0 side_bb = side_cc ang_C =",
"(90.0, 0.0, 90.0, True) elif abs(side_cc % 360.0) < EpsTest: expRes = (90.0,",
"* sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA =",
"other quadrants; they're based on what works, so are somewhat suspect if side_bb",
"test were incorrect - side_aa normal + side_cc tiny: table was right but",
"when this occurs) then angles a and c cannot be computed. In this",
"could not be computed (and are both set to 90); bb will be",
"0.0): if side_aa < EpsTest: expRes = (90.0, 180.0, 90.0, True) elif 180.0",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~ 180, B = various, c various:",
"opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0, 180.0, 90.0, True)",
"c, C = 180 - B for side_aa in (-Eps, 0.0, Eps): for",
"ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 0, B = various, a",
">> Eps, B varies, c = 90 # expect: C = 180 -",
"but avoid poles # tan C = tan c / sin a #",
"0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps,",
"angles comparing things like 359.999... to 0, compare sin and cos of ang_A",
"sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa",
"TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb to unknownAng; side_bb may be",
"+/- c) / 2, and use to compute angles a and c h_sum_AC",
"given the remaining quantities. Inputs: - side_aa side aa; range of sides: [0,",
"sin_h_B * cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2 = sin_h_B * sin_h_sum_aacc",
"ROwen Bug fix: unknownAng should always be true if side_aa and side_cc are",
"180 where: - !pole means not nearly 0 and not nearly 180 (modulo",
"= opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc *",
"sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B *",
"= 90.0. Also side_bb = 0.0, which is essentially correct. Note that the",
"- side_aa ang_C = 180.0 else: # + # compute angles a and",
"= various, c various: # if c nearly 180 (modulo 360): expect C",
"= 90, b = 0, A = 90, unknownAng # if a nearly",
"(90.0, 0.0, 90.0, True) elif abs((180.0 - side_aa) % 360.0) < EpsTest: expRes",
"side_bb = 180.0 - side_cc ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: #",
"input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0] < 0.0",
"= side_aa ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly",
"0.0 or actualOutput[2] >= 360.0: print(\"failed on input:\", testInput) print(\"one or more angles",
"numerator and denominator are too small # to accurately determine angle = atan2",
"sin_h_sum_BA # numerator and denominator for analogy for bb + aa num4 =",
"elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo 360) and side_aa",
"unknown # if c << a: expect A = 180, b = c",
"consisting of: # - the input argument # - the expected result: ang_C,",
"side_bb = 180.0 - side_aa ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: #",
"to allow computation, raises ValueError - If side bb is near 0 or",
"180-ang_B side_aa 0 !pole any ~180 ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90)",
"side_bb = side_cc ang_C = 180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: #",
"360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (0.0,",
"formatted as follows: # a list of entries, each consisting of: # -",
"False) # a ~ 0, B = various, c various: # if c",
"unknownAng # if c nearly 0 (modulo 360): expect C = 90, b",
"+/- cc) / 2) and cos((aa +/- cc) / 2) sin_h_sum_aacc = sin_h_aa",
"side_cc are nearly 0 or 180 but that was not happening if ang_B",
"of 0. Bug fix: in some cases side_bb may be 180 and ang_A",
"- Eps, 180, 180 + Eps, 256, 359): expRes = (0.0, side_cc +",
"< 0.0 or actualOutput[1] >= 360.0 \\ or actualOutput[2] < 0.0 or actualOutput[2]",
"any ~0 unknown(90) 180 unknown(90) ~180 any ~180 unknown(90) 0 unknown(90) ~180 any",
"~180 any ~180 unknown(90) 0 unknown(90) ~180 any !pole 180 180-side_cc ang_B !pole",
"be true if side_aa and side_cc are nearly 0 or 180 but that",
"a nearly 0 (modulo 360): expect C = 90, b = 180, A",
"ang_C < 0: ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb,",
"~ 0, B = various, c various: # if c nearly 0 (modulo",
"expect A = 180 - B, b = a, C = 0 for",
"various, c various: # if c nearly 0 (modulo 360): expect C =",
"and ang_A and ang_C unknown. Improved accuracy in some corner cases; all unit",
"A = 90, unknownAng # else: expect A = 180 - B, b",
"that the sum ang_A + ang_C is 180, which is also essentially correct.",
"determine angle = atan2 (num, den), give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy)",
"and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2)",
"compute angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d",
"etc. Warnings: Allowing angles in the 3rd and 4th quadrants is unusual. References:",
"- side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a = 90, B varies",
"sum of ang_A and ang_C is correct and the value of side_bb is",
"= angSideAng(*testInput) # to handle angles comparing things like 359.999... to 0, compare",
"nearly 180 (modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc is",
"side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb = 2.0",
"allow computation, raises ValueError - If side bb is near 0 or 180",
"+= [ # 90/90/90 triangle ((90, 90, 90), (90, 90, 90)), # inputs",
"ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa 180",
"Also side_bb = 0.0, which is essentially correct. Note that the sum ang_A",
"0. Bug fix: in some cases side_bb may be 180 and ang_A and",
"[0, 180] - ang_B angle b; range of angles: [0, 360) - side_cc",
"opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5)",
"return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly",
"* sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA =",
"analogies # - # compute sin((aa +/- cc) / 2) and cos((aa +/-",
"360) return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is",
"(modulo 360): expect C = 90, b = 0, A = 90, unknownAng",
"side_bb = side_aa ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is",
"= a - c, C = 180 for side_aa in (179.9, -27.0, 27.0,",
"= opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa *",
"side_cc, 0.0) else: expRes = (0.0, side_cc - side_aa, 180.0) for ang_B in",
"* 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B * cos_h_A +",
"c - unknownAng if true, angle A and angle C could not be",
"if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0,",
"side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc %",
"zero_bb to unknownAng; side_bb may be 180 instead of 0. Bug fix: in",
"# print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc",
"180, 180 + Eps, 256, 359): expRes = (180.0 - ang_B, side_aa +",
"unknownAng # if a nearly 180: expect C = 90, b = 180,",
"0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly small but >> Eps, B",
"90, unknownAng # if c nearly 180 (modulo 360): expect C = 90,",
"c / sin a # tan c = (tan a / sinA *",
"ang_A, [unknownAng] (unknownAng defaults to False) # a ~ 0, B = various,",
"nearly 0. Fixed by evaluating ang_B special cases after side_aa and side_cc special",
"- all relations are modulo 360. For example ~0 means approximately zero, 360,",
"abs (den4): # use Napier's analogy for bb - aa side_bb = 2.0",
"ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0, 180.0 +",
"elif abs((side_cc - 180) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0,",
"c cannot be computed. In this case \"unknownAng\" = true, ang_A = ang_C",
"of entries, each consisting of: # - the input argument # - the",
"bb will be 0 or 180 Error Conditions: - If the inputs are",
"sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5)",
"- Eps, 180.0, 180.0 + Eps): for ang_B in (0.0, Eps, 32.0, 97.0,",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # a = 90, B varies but not nearly",
"side_cc - side_aa ang_C = 180.0 else: # + # compute angles a",
"=\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1,",
"/ 2) = num/den num1 = cos_h_B * cos_h_diff_aacc den1 = sin_h_B *",
"atan2 (num, den), give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1)",
"= 180, b = 180 - c, C = B for side_aa in",
"analogy for bb - aa num3 = sin_h_cc * sin_h_diff_BA den3 = cos_h_cc",
"~0 unknown(90) 0 unknown(90) ~0 any ~180 unknown(90) 180 unknown(90) ~0 any !pole",
"# B is nearly 0 (modulo 360) if abs(side_aa - side_cc) < opscore.RO.SysConst.FAccuracy:",
"ang_C: return (90.0, 0.0, 90.0, True) elif side_cc < side_aa: ang_A = 180.0",
"to 90); bb will be 0 or 180 Error Conditions: - If the",
"expect A = 180, b = c - a, C = 0 #",
"any ~0 unknown(90) 0 unknown(90) ~0 any ~180 unknown(90) 180 unknown(90) ~0 any",
"the angle is unknown and is abitrarily set to 90 degrees. The sum",
"= 90, unknownAng # if a nearly 180 (modulo 360): expect C =",
"360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0,",
"if c nearly 0 (modulo 360): expect C = 90, b = 180,",
"side_aa in (180.0 - Eps, 180.0, 180.0 + Eps): for ang_B in (0.0,",
"based on what works, so are somewhat suspect if side_bb < 0: side_bb",
"~0 ~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa 180 side_aa-cc 0 any ~0",
"!pole 0 side_cc 180-ang_B ~180 any ~0 unknown(90) 180 unknown(90) ~180 any ~180",
"raise RuntimeError(\"Bug: can't compute ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa,",
"A = 180, b = 180 - c, C = B for side_aa",
"so are somewhat suspect if side_bb < 0: side_bb = - side_bb if",
"to unknownAng; side_bb may be 180 instead of 0. Bug fix: in some",
"(modulo 360); cannot compute ang_A or ang_C: return (90.0, 0.0, 90.0, True) elif",
"if a nearly 180: expect C = 90, b = 180, A =",
"tweaks to handle the other quadrants ang_B = 90.0 for side_aa in (1.0,",
"c nearly 180 (modulo 360): expect C = 90, b = 180, A",
"angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical triangle for two angles and the",
"- side_aa, 180.0) for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes))",
"* 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo 360)",
"works, so are somewhat suspect if side_bb < 0: side_bb = - side_bb",
"opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0, 180.0, 90.0, True)",
"\\ or actualOutput[1] < 0.0 or actualOutput[1] >= 360.0 \\ or actualOutput[2] <",
"B varies but not nearly 0 or 360, c fairly small but >>",
"90, unknownAng # if a nearly 180 (modulo 360): expect C = 90,",
"and the angle is unknown and is abitrarily set to 90 degrees. The",
"elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0,",
"all unit tests now pass. Greatly expanded the unit tests. 2010-08-04 ROwen Bug",
"outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in testData: if len(expectedOutput) <",
"order they are handled): side_aa ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any",
"(23, 90, 180 - Eps, 180, 180 + Eps, 256, 359): expRes =",
"sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc",
"~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa 180 side_aa-cc 0 any ~0 >side_aa",
"(-Eps, 0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 -",
"True) else: expRes = (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes))",
"= processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\",",
"and cos((aa +/- cc) / 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa",
"side_cc in (180.0 - Eps, 180.0): for ang_B in (0.0, Eps, 32.0, 97.0,",
"num/den num1 = cos_h_B * cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2 =",
"they are handled): side_aa ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0",
"(num3, den3) + side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) -",
"- 45.0, side_aa - Eps, side_aa, side_aa + Eps, side_aa + 45.0): if",
"= sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc",
"sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa *",
"= (90.0, 180.0, 90.0, True) else: expRes = (0.0, side_cc - side_aa, 180.0",
"for bb + aa) # - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5)",
"0, A = 90, unknownAng # if c nearly 180 (modulo 360): expect",
"True) elif abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True)",
"opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in testData: if len(expectedOutput)",
"256, 359): expRes = (180.0 - ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0)",
"1.0e-10): for ang_B in (23, 90, 180 - Eps, 180, 180 + Eps,",
"= 180 - B, b = c + a cos(B), A ~= 0",
"- ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B small, a = any not",
"opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C),",
"= (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a =",
"sin and cos of ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput)",
"fix: mis-handled two cases: - side_aa tiny + side_cc normal: special case table,",
"actualOutput[1] < 0.0 or actualOutput[1] >= 360.0 \\ or actualOutput[2] < 0.0 or",
"0 side_cc-aa 180 where: - !pole means not nearly 0 and not nearly",
"+ sin_h_B * sin_h_A # numerator and denominator for analogy for bb -",
"True) elif side_cc < side_aa: expRes = (180.0, side_aa - side_cc, 0.0) else:",
"den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B",
"actualOutput) print() if actualOutput[0] < 0.0 or actualOutput[0] >= 360.0 \\ or actualOutput[1]",
"angle b; range of angles: [0, 360) - side_cc side cc Returns a",
"< 0, (but should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1,",
"ang_B, side_cc), expRes)) # B small, a = any not small, c =",
"nearly 180 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy:",
"return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly",
"a cos(B), A ~= 0 side_cc = 90.0 for side_aa in (1.0e-12, 1.0e-10):",
"1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30",
"90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360)",
"is for bb - aa, one for bb + aa) # - #",
"side_cc is nearly zero (modulo 360) and side_aa is not ang_A = 180.0",
"180 180-side_cc ang_B !pole any ~0 180-ang_B side_aa 0 !pole any ~180 ang_B",
"History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb",
"sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa *",
"denominator, where tan((a +/- c) / 2) = num/den num1 = cos_h_B *",
"90, b = 0, A = 90, unknownAng # if c nearly 0",
"c, C = B for side_cc in (180.0 - Eps, 180.0): for ang_B",
"(180.0 - ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes))",
"~180 unknown(90) 0 unknown(90) ~180 any !pole 180 180-side_cc ang_B !pole any ~0",
"cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B *",
"testData = [] # test data is formatted as follows: # a list",
"a = 90, B varies but not nearly 0 or 360, c fairly",
"0 or 180 (modulo 360) ang_A = 180.0 side_bb = 180.0 - side_cc",
"side_aa ~= side_cc (modulo 360); cannot compute ang_A or ang_C: return (90.0, 0.0,",
"bb - aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else:",
"import opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical triangle",
"ang_A = h_sum_AC + h_diff_AC ang_C = h_sum_AC - h_diff_AC # + #",
"cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc # compute numerator and denominator, where",
"side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if side_aa <",
"Fixed by evaluating ang_B special cases after side_aa and side_cc special cases. Tweaked",
"unknown(90) ~180 any ~180 unknown(90) 0 unknown(90) ~180 any !pole 180 180-side_cc ang_B",
"- ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~ 180, B = various,",
"be computed. In this case \"unknownAng\" = true, ang_A = ang_C = 90.0.",
"- side_bb if ang_A < 0: ang_A = 180.0 + ang_A if ang_C",
"0.0, which is essentially correct. Note that the sum ang_A + ang_C is",
"ang_C = 180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly",
"side_cc), expRes)) # right triangle: B = 90, a and c vary but",
"(False,) actualOutput = angSideAng(*testInput) # to handle angles comparing things like 359.999... to",
"def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical triangle for two angles and",
"means approximately zero, 360, etc. Warnings: Allowing angles in the 3rd and 4th",
"* cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA # compute side bb if abs",
"follows: # a list of entries, each consisting of: # - the input",
"# if c != a: expect A = 90, b = 0, C",
"180.0, 90.0, True) else: # side_cc is not nearly 0 or 180 ang_A",
"0, b = a - c, C = 180 for side_aa in (179.9,",
"/ 2) sin_h_sum_aacc = sin_h_aa * cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc =",
"# print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2, den2",
"32.0, 97.0, 179.0, 180.0 - Eps, 180.0, 180.0 + Eps, 210.0, 360.0 -",
"sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B",
"cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2,",
"unknown(90) any ~0 <side_aa 180 side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa 180",
"tan((a +/- c) / 2) = num/den num1 = cos_h_B * cos_h_diff_aacc den1",
"(in the order they are handled): side_aa ang_B side_cc ang_A side_bb ang_C ----------------------------------------------------------------",
"side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps =",
"the unit tests. 2010-08-04 ROwen Bug fix: mis-handled two cases: - side_aa tiny",
"* sin_h_sum_BA # numerator and denominator for analogy for bb + aa num4",
"to clarify the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B",
"(90.0, 0.0, 90.0, True) elif side_cc < side_aa: ang_A = 180.0 side_bb =",
"may be 180 instead of 0. Bug fix: in some cases side_bb may",
"tests now pass. Greatly expanded the unit tests. 2010-08-04 ROwen Bug fix: mis-handled",
"(180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if side_aa < EpsTest: expRes",
"two Napier's analogies # (one is for bb - aa, one for bb",
"side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa 180 where: - !pole means not",
"+ Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps,",
"0, C = 90, unknown # if c << a: expect A =",
"compute side bb using one of two Napier's analogies # (one is for",
"180, A = 90, unknownAng # else: expect A = 180 - B,",
"c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print",
"- h_diff_AC # + # compute side bb using one of two Napier's",
"print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc #",
"= h_sum_AC - h_diff_AC # + # compute side bb using one of",
"0.0 side_bb = side_cc ang_C = 180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy:",
"= (90.0, 0.0, 90.0, True) elif abs((180.0 - side_aa) % 360.0) < EpsTest:",
"expRes = (90.0, 180.0, 90.0, True) else: expRes = (0.0, side_cc - side_aa,",
"3rd and 4th quadrants is unusual. References: Selby, Standard Math Tables, crc, 15th",
"side_aa < EpsTest: expRes = (90.0, 180.0, 90.0, True) elif 180.0 - side_aa",
"aa, one for bb + aa) # - # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A",
"= 90, b = 0, C = 90, unknown # if c <<",
"side_cc is nearly 0 (modulo 360) return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc)",
"c, C = 180 for side_aa in (179.9, -27.0, 27.0, 0.1): for side_cc",
"(90.0, 180.0, 90.0, True) else: expRes = (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa,",
"normal: special case table, code and unit test were incorrect - side_aa normal",
"ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90) ~0",
"side_cc < side_aa: expRes = (180.0, side_aa - side_cc, 0.0) else: expRes =",
"opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0, 0.0, 90.0, True)",
"0.0, 90.0, True) else: expRes = (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B,",
"ang_C angle c - unknownAng if true, angle A and angle C could",
"angles a and c cannot be computed. In this case \"unknownAng\" = true,",
"< side_aa: ang_A = 180.0 side_bb = side_aa - side_cc ang_C = 0.0",
"sides: [0, 180] - ang_B angle b; range of angles: [0, 360) -",
"~0 any ~180 unknown(90) 180 unknown(90) ~0 any !pole 0 side_cc 180-ang_B ~180",
"cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA",
"# test data is formatted as follows: # a list of entries, each",
"else: expect A = 180 - B, b = a, C = 0",
"else: expRes = (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"numerator and denominator for analogy for bb + aa num4 = sin_h_cc *",
"EpsTest: expRes = (90.0, 0.0, 90.0, True) elif side_cc < side_aa: expRes =",
"> abs (num4) + abs (den4): # use Napier's analogy for bb -",
"ang_C is 180, which is also essentially correct. Special Cases (in the order",
"side_cc side cc Returns a tuple containing: - ang_A angle a - side_bb",
"compare sin and cos of ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual =",
"a nearly 180 (modulo 360): expect C = 90, b = 0, A",
"180.0 else: # + # compute angles a and c using Napier's analogies",
"elif abs((180.0 - side_aa) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0,",
"(Spherical Trig.) History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed",
"a fairly small but >> Eps, B varies, c = 90 # expect:",
"* cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2",
"cos_h_A + sin_h_B * sin_h_A # numerator and denominator for analogy for bb",
"poles # tan C = tan c / sin a # tan c",
"A = 0, b = a - c, C = 180 - B",
"359): expRes = (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa,",
"A = 180, b = c - a, C = 0 # if",
"abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0, 180.0,",
"0 (modulo 360): expect C = 90, b = 180, A = 90,",
"ang_C unknown. Improved accuracy in some corner cases; all unit tests now pass.",
"(((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <=",
"to 0, compare sin and cos of ang_A and ang_C: procExpected = processOutput(expectedOutput)",
"side connecting them, given the remaining quantities. Inputs: - side_aa side aa; range",
"cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc,",
"else: ang_A = 0.0 side_bb = side_cc - side_aa ang_C = 180.0 else:",
"for side_cc in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc))",
"= 90, unknownAng # else: expect A = 0, b = a -",
"side_aa ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly 0",
"True) elif abs((side_cc - 180) % 360.0) < EpsTest: expRes = (90.0, 180.0,",
"90.0, True) elif abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0,",
"are too small to allow computation, raises ValueError - If side bb is",
"what works, so are somewhat suspect if side_bb < 0: side_bb = -",
"- side_cc side cc Returns a tuple containing: - ang_A angle a -",
"side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~",
"180 Error Conditions: - If the inputs are too small to allow computation,",
"or 180 (modulo 360) ang_A = 180.0 side_bb = 180.0 - side_cc ang_C",
"# c ~ 180, B = various, a various: # if a nearly",
"(180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 0,",
"opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B small, a =",
"b = 180, A = 90, unknownAng # else: expect A = 0,",
"C = 0 for side_cc in (0.0, Eps): for ang_B in (0.0, Eps,",
"ang_B side_bb = 180.0 - side_aa ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy:",
"= opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B * sin_h_A",
"= (0.0, side_cc - side_aa, 180.0) for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa,",
"unknown(90) ~0 any !pole 0 side_cc 180-ang_B ~180 any ~0 unknown(90) 180 unknown(90)",
"(90.0, 0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0",
"0 or 180 (see Special Cases below for when this occurs) then angles",
"0 # if c >> a: expect A = 0, b = a",
"side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\":",
"A = 0, b = a - c, C = 180 for side_aa",
"opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a fairly small but >> Eps,",
"0.0 or actualOutput[0] >= 360.0 \\ or actualOutput[1] < 0.0 or actualOutput[1] >=",
"for side_cc in (180.0 - Eps, 180.0): for ang_B in (0.0, Eps, 32.0,",
"is not ang_A = 180.0 - ang_B side_bb = side_aa ang_C = 0.0",
"side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a = 90, B varies but",
"elif 180.0 - side_aa < EpsTest: expRes = (90.0, 0.0, 90.0, True) else:",
"means not nearly 0 and not nearly 180 (modulo 360) - unknown(90) means",
"small but >> Eps # expect: A = 180 - B, b =",
"cos_h_cc * cos_h_sum_BA # compute side bb if abs (num3) + abs (den3)",
"- Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0 - side_cc) % 360.0) <",
"expRes = (90.0, 0.0, 90.0, True) elif side_cc < side_aa: expRes = (180.0,",
"the value of side_bb is correct to within epsilon. - all relations are",
"- B, b = c + a cos(B), A ~= 0 side_cc =",
"0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) and",
"side_aa + Eps, side_aa + 45.0): if abs(side_cc - side_aa) < EpsTest: expRes",
"270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)),",
"procExpected = processOutput(expectedOutput) procActual = processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on",
"ang_A = 0.0 side_bb = side_cc ang_C = 180.0 - ang_B elif abs(cos_h_aa)",
"+ ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData += [ # 90/90/90",
"180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo",
"Solves a spherical triangle for two angles and the side connecting them, given",
"= 90, b = 0, A = 90, unknownAng # else: expect A",
"180 - B, b = a, C = 0 for side_cc in (0.0,",
"= opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print",
"2010-07-30 ROwen Changed output zero_bb to unknownAng; side_bb may be 180 instead of",
"abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) and side_aa is",
"is formatted as follows: # a list of entries, each consisting of: #",
"print \"num1, den1, num2, den2 =\", num1, den1, num2, den2 # print \"h_sum_AC,",
"= (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~",
"any !pole 180 180-side_cc ang_B !pole any ~0 180-ang_B side_aa 0 !pole any",
"or 180 but that was not happening if ang_B was nearly 0. Fixed",
"cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B *",
"* opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4,",
"is nearly 180 (modulo 360) and side_aa is not ang_A = ang_B side_bb",
"c various: # if c nearly 0 (modulo 360): expect C = 90,",
"be computed (and are both set to 90); bb will be 0 or",
"if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo 360) if abs(sin_h_cc)",
"sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B",
"EpsTest = Eps * 1.001 testData = [] # test data is formatted",
"compute angles a and c using Napier's analogies # - # compute sin((aa",
"# compute angles a and c using Napier's analogies # - # compute",
"various, a various: # if a nearly 0: expect C = 90, b",
"up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs (den1) <= opscore.RO.SysConst.FAccuracy)) or ((abs",
"- Eps, 360.0): for side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps,",
"ang_A = 0.0 side_bb = side_cc - side_aa ang_C = 180.0 else: #",
"0, b = a - c, C = 180 - B for side_aa",
"# if a nearly 180: expect C = 90, b = 180, A",
"= 90, b = 180, A = 90, unknownAng # else: expect A",
"ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo",
"expectedOutput + (False,) actualOutput = angSideAng(*testInput) # to handle angles comparing things like",
"abitrarily set to 90 degrees. The sum of ang_A and ang_C is correct",
"= 90, unknownAng # else: expect A = 180, b = 180 -",
"(side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B small,",
"not happening if ang_B was nearly 0. Fixed by evaluating ang_B special cases",
"180, 180 + Eps, 256, 359): expRes = (0.0, side_cc + (side_aa *",
"C = 180 - B, b = c + a cos(B), A ~=",
"0 (modulo 360): expect C = 90, b = 0, A = 90,",
"45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135),",
"tan c / sin a # tan c = (tan a / sinA",
"if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest =",
"in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle: B =",
"- side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~ 180,",
"opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: #",
"for side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0",
"* cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B",
"A = 180 - B, b = a + c cos(B), C ~=",
"if actualOutput[0] < 0.0 or actualOutput[0] >= 360.0 \\ or actualOutput[1] < 0.0",
"be 0 or 180 Error Conditions: - If the inputs are too small",
"<= opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise",
"180 (see Special Cases below for when this occurs) then angles a and",
"1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1,",
"0 side_aa = 90.0 for side_cc in (1.0e-12, 1.0e-10): for ang_B in (23,",
"= opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc))",
"and C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute (a",
"a + c cos(B), C ~= 0 side_aa = 90.0 for side_cc in",
"not ang_A = ang_B side_bb = 180.0 - side_aa ang_C = 180.0 elif",
"and denominator, where tan((a +/- c) / 2) = num/den num1 = cos_h_B",
"num2, den2 =\", num1, den1, num2, den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC,",
"cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A - cos_h_B *",
"side_cc), expRes)) # c ~ 180, B = various, a various: # if",
"= 90 # expect: C = 180 - B, b = c +",
"!pole any ~180 ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90) 0 unknown(90) any",
"if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual",
"to within epsilon. - all relations are modulo 360. For example ~0 means",
"for when this occurs) then angles a and c cannot be computed. In",
"180 - B for side_aa in (-Eps, 0.0, Eps): for ang_B in (0.0,",
"angle C could not be computed (and are both set to 90); bb",
"and side_cc special cases. Tweaked the documentation to clarify the special cases. \"\"\"",
"* cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B",
"analogies # (one is for bb - aa, one for bb + aa)",
"97.0, 179.0, 180.0 - Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps,",
"+ ang_C is 180, which is also essentially correct. Special Cases (in the",
"of angles: [0, 360) - side_cc side cc Returns a tuple containing: -",
"0.0, 90.0, True) elif abs((180.0 - side_aa) % 360.0) < EpsTest: expRes =",
"a - side_bb side bb - ang_C angle c - unknownAng if true,",
"Note that the sum ang_A + ang_C is 180, which is also essentially",
"179.0, 180.0 - Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0):",
"occurs) then angles a and c cannot be computed. In this case \"unknownAng\"",
"90, unknownAng # if a nearly 180: expect C = 90, b =",
"# if a nearly 0 (modulo 360): expect C = 90, b =",
"= 90, b = 0, A = 90, unknownAng # if c nearly",
"~ 180, B = various, c various: # if c nearly 180 (modulo",
"for side_cc in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 - Eps,",
"0. Fixed by evaluating ang_B special cases after side_aa and side_cc special cases.",
"opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\" %",
"C = tan c / sin a # tan c = (tan a",
"# print \"num1, den1, num2, den2 =\", num1, den1, num2, den2 # print",
"# - the expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to False)",
"for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0, 180.0",
"in (side_aa - 45.0, side_aa - Eps, side_aa, side_aa + Eps, side_aa +",
"handled): side_aa ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0",
"cos_h_sum_BA # compute side bb if abs (num3) + abs (den3) > abs",
"RuntimeError(\"Bug: can't compute ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B,",
"quadrants ang_B = 90.0 for side_aa in (1.0, 20.0, 45.0, 90, 110.0, 179.0):",
"(num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False)",
"print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0] < 0.0 or actualOutput[0]",
"< EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (0.0, side_cc",
"sin_h_A # numerator and denominator for analogy for bb - aa num3 =",
"179.0, 47.0, Eps, 0.0): if abs(side_aa % 360.0) < EpsTest: expRes = (90.0,",
"0 (modulo 360) and side_aa ~= side_cc (modulo 360); cannot compute ang_A or",
"180 - c, C = B for side_cc in (180.0 - Eps, 180.0):",
"/ sin a # tan c = (tan a / sinA * sinb)",
"a and c using Napier's analogies # - # compute sin((aa +/- cc)",
"=\", num1, den1, num2, den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A",
"# side_cc is nearly 180 (modulo 360) and side_aa is not ang_A =",
"ang_B, side_cc), expRes)) # a = 90, B varies but not nearly 0",
"= opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero",
"2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d",
"Eps, side_aa, side_aa + Eps, side_aa + 45.0): if abs(side_cc - side_aa) <",
"processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput",
"be 180 instead of 0. Bug fix: in some cases side_bb may be",
"side_cc)) # compute (a +/- c) / 2, and use to compute angles",
"0 (modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc is not",
"= [\"angSideAng\"] import opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a",
"< opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0, 0.0, 90.0,",
"side_cc 180-ang_B ~180 any ~0 unknown(90) 180 unknown(90) ~180 any ~180 unknown(90) 0",
"side_aa ang_C = 180.0 else: # + # compute angles a and c",
"(modulo 360) - unknown(90) means unknownAng is set True and the angle is",
"any ~180 ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90) 0 unknown(90) any ~0",
"h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C = h_sum_AC - h_diff_AC #",
"# a list of entries, each consisting of: # - the input argument",
"- side_aa normal + side_cc tiny: table was right but code and unit",
"testInput, expectedOutput in testData: if len(expectedOutput) < 4: expectedOutput = expectedOutput + (False,)",
"180.0 side_bb = side_aa - side_cc ang_C = 0.0 else: ang_A = 0.0",
"0 !pole any ~180 ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90) 0 unknown(90)",
"any ~0 <side_aa 180 side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa 180 where:",
"bb - aa, one for bb + aa) # - # preliminaries sin_h_A",
"inputs are too small to allow computation, raises ValueError - If side bb",
"on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0] <",
"side_aa is nearly 180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is",
"- ang_A angle a - side_bb side bb - ang_C angle c -",
"are handled): side_aa ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90)",
"small, c = any not small: # if c != a: expect A",
"side_aa) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes",
"ang_B, side_cc), expRes)) # a fairly small but >> Eps, B varies, c",
"other quadrants ang_B = 90.0 for side_aa in (1.0, 20.0, 45.0, 90, 110.0,",
"< EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((180.0 - side_aa) %",
">= 360.0 \\ or actualOutput[1] < 0.0 or actualOutput[1] >= 360.0 \\ or",
"side_cc-aa 180 where: - !pole means not nearly 0 and not nearly 180",
"ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo",
"0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo",
"(modulo 360) and side_aa is not ang_A = 180.0 - ang_B side_bb =",
"= 180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180",
"= side_aa - side_cc ang_C = 0.0 else: ang_A = 0.0 side_bb =",
"< opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy:",
"is unknown and is abitrarily set to 90 degrees. The sum of ang_A",
"the 3rd and 4th quadrants is unusual. References: Selby, Standard Math Tables, crc,",
"ang_A = 180.0 + ang_A if ang_C < 0: ang_C = 180.0 +",
"- side_bb side bb - ang_C angle c - unknownAng if true, angle",
"then angles a and c cannot be computed. In this case \"unknownAng\" =",
"cos_h_cc + cos_h_aa * sin_h_cc sin_h_diff_aacc = sin_h_aa * cos_h_cc - cos_h_aa *",
"for bb + aa num4 = sin_h_cc * cos_h_diff_BA den4 = cos_h_cc *",
"0 unknown(90) ~0 any ~180 unknown(90) 180 unknown(90) ~0 any !pole 0 side_cc",
"# else: expect A = 0, b = a - c, C =",
"180.0, 90.0, True) else: expRes = (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B,",
"for side_aa in (1.0, 20.0, 45.0, 90, 110.0, 179.0): for side_cc in (1.0,",
"cos_h_cc * sin_h_sum_BA # numerator and denominator for analogy for bb + aa",
"the sum ang_A + ang_C is 180, which is also essentially correct. Special",
"90, 90), (90, 90, 90)), # inputs that might cause side_bb < 0,",
"90, b = 180, A = 90, unknownAng # else: expect A =",
"computed (and are both set to 90); bb will be 0 or 180",
"expRes = (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B,",
"and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and C with",
"\"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa # print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print",
"# side_cc is nearly 0 (modulo 360) return (90.0, 0.0, 90.0, True) elif",
"should always be true if side_aa and side_cc are nearly 0 or 180",
"on what works, so are somewhat suspect if side_bb < 0: side_bb =",
"and not nearly 180 (modulo 360) - unknown(90) means unknownAng is set True",
"360) and side_aa is not ang_A = ang_B side_bb = 180.0 - side_aa",
"!pole means not nearly 0 and not nearly 180 (modulo 360) - unknown(90)",
"= sin_h_B * cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc den2 = sin_h_B *",
"+ side_cc tiny: table was right but code and unit test had errors",
"- B for side_aa in (-Eps, 0.0, Eps): for ang_B in (0.0, Eps,",
"sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B =",
"4: expectedOutput = expectedOutput + (False,) actualOutput = angSideAng(*testInput) # to handle angles",
"sin a # tan c = (tan a / sinA * sinb) #",
"some tweaks to handle the other quadrants ang_B = 90.0 for side_aa in",
"else: expRes = (0.0, side_cc - side_aa, 180.0) for ang_B in (-Eps, 0.0,",
"360): expect C = 90, b = 0, A = 90, unknownAng #",
"0.1): for side_cc in (side_aa - 45.0, side_aa - Eps, side_aa, side_aa +",
"= (90.0, 180.0, 90.0, True) else: expRes = (180.0, 180.0 - side_cc, ang_B)",
"if abs((180.0 - side_cc) % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0,",
"nearly 180: expect C = 90, b = 180, A = 90, unknownAng",
"90.0, True) elif abs((180.0 - side_aa) % 360.0) < EpsTest: expRes = (90.0,",
"if c nearly 180 (modulo 360): expect C = 90, b = 180,",
"cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA # compute side bb if abs (num3)",
"not nearly 0 and not nearly 180 (modulo 360) - unknown(90) means unknownAng",
"180.0 - side_aa ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is",
"argument # - the expected result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to",
"[] # test data is formatted as follows: # a list of entries,",
"for analogy for bb - aa num3 = sin_h_cc * sin_h_diff_BA den3 =",
"actualOutput[0] >= 360.0 \\ or actualOutput[1] < 0.0 or actualOutput[1] >= 360.0 \\",
"true, angle A and angle C could not be computed (and are both",
"if c >> a: expect A = 0, b = a - c,",
"< 0: side_bb = - side_bb if ang_A < 0: ang_A = 180.0",
"varies, c = 90 # expect: C = 180 - B, b =",
"import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest = Eps * 1.001 testData",
"h_sum_AC - h_diff_AC # + # compute side bb using one of two",
"some corner cases; all unit tests now pass. Greatly expanded the unit tests.",
"sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B * sin_h_A # numerator and",
"some cases side_bb may be 180 and ang_A and ang_C unknown. Improved accuracy",
"opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves a spherical triangle for two angles",
"nearly zero (modulo 360) and side_aa is not ang_A = 180.0 - ang_B",
"Eps, side_aa + 45.0): if abs(side_cc - side_aa) < EpsTest: expRes = (90.0,",
"< opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0, 180.0, 90.0,",
"180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa % 360.0) < EpsTest:",
"cos_h_aa * cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc +",
"den3) + side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa",
"(90.0, 0.0, 90.0, True) elif side_cc < side_aa: expRes = (180.0, side_aa -",
"within epsilon. - all relations are modulo 360. For example ~0 means approximately",
"is essentially correct. Note that the sum ang_A + ang_C is 180, which",
"cases: - side_aa tiny + side_cc normal: special case table, code and unit",
"= (90.0, 0.0, 90.0, True) elif abs(side_cc % 360.0) < EpsTest: expRes =",
"180 (modulo 360): expect C = 90, b = 0, A = 90,",
"ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle: B",
"side_bb, ang_C))) testData += [ # 90/90/90 triangle ((90, 90, 90), (90, 90,",
">= 360.0: print(\"failed on input:\", testInput) print(\"one or more angles out of range:\",",
"~ 0, B = various, a various: # if a nearly 0: expect",
"135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec):",
"analogy for bb - aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) +",
"179.0, 47.0, Eps, 0.0): if abs((180.0 - side_cc) % 360.0) < EpsTest: expRes",
"too small to allow computation, raises ValueError - If side bb is near",
"side_aa in (179.9, -27.0, 27.0, 0.1): for side_cc in (side_aa - 45.0, side_aa",
"90, 180 - Eps, 180, 180 + Eps, 256, 359): expRes = (180.0",
"0.0, 90.0, True) elif side_cc < side_aa: expRes = (180.0, side_aa - side_cc,",
"( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in testData:",
"<= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\"",
"sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa",
"special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B *",
"a various: # if a nearly 0: expect C = 90, b =",
"= num/den num1 = cos_h_B * cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2",
"unknownAng # if c nearly 180 (modulo 360): expect C = 90, b",
"or actualOutput[0] >= 360.0 \\ or actualOutput[1] < 0.0 or actualOutput[1] >= 360.0",
"180, b = c - a, C = 0 # if c >>",
"(180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc % 360.0) <",
"EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs(side_cc % 360.0) < EpsTest:",
"ang_B, side_cc)) # compute (a +/- c) / 2, and use to compute",
"(modulo 360) return (90.0, 0.0, 90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc",
"each consisting of: # - the input argument # - the expected result:",
"180 (modulo 360): expect C = 90, b = 180, A = 90,",
"opscore.RO.MathUtil.sind(side_aa) sin_h_cc = opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B *",
"handle angles comparing things like 359.999... to 0, compare sin and cos of",
"180, which is also essentially correct. Special Cases (in the order they are",
"180-side_cc ang_B !pole any ~0 180-ang_B side_aa 0 !pole any ~180 ang_B 180-side_aa",
"4th quadrants is unusual. References: Selby, Standard Math Tables, crc, 15th ed, 1967,",
"27.0, 0.1): for side_cc in (side_aa - 45.0, side_aa - Eps, side_aa, side_aa",
"cases side_bb may be 180 and ang_A and ang_C unknown. Improved accuracy in",
"den3 = cos_h_cc * sin_h_sum_BA # numerator and denominator for analogy for bb",
"quantities. Inputs: - side_aa side aa; range of sides: [0, 180] - ang_B",
"side_cc (modulo 360); cannot compute ang_A or ang_C: return (90.0, 0.0, 90.0, True)",
"/ sinA * sinb) # with some tweaks to handle the other quadrants",
"= 0.0 side_bb = side_cc - side_aa ang_C = 180.0 else: # +",
"# these tweaks handle other quadrants; they're based on what works, so are",
"Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps, 180.0,",
"opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: #",
"opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import opscore.RO.SeqUtil",
"if a nearly 0: expect C = 90, b = 0, A =",
"ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly 0 (modulo",
"180 + Eps, 256, 359): expRes = (0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)),",
"+ ang_A if ang_C < 0: ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B,",
"B for side_cc in (180.0 - Eps, 180.0): for ang_B in (0.0, Eps,",
"the documentation to clarify the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc =",
"cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa *",
"[unknownAng] (unknownAng defaults to False) # a ~ 0, B = various, c",
"90, unknown # if c << a: expect A = 180, b =",
"= 180 - B, b = a, C = 0 for side_cc in",
"or actualOutput[1] >= 360.0 \\ or actualOutput[2] < 0.0 or actualOutput[2] >= 360.0:",
"(90.0, 0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180",
"* cos_h_cc - sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa",
"side_bb < 0, (but should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45,",
"opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in testData: if",
"side_bb side bb - ang_C angle c - unknownAng if true, angle A",
"c cos(B), C ~= 0 side_aa = 90.0 for side_cc in (1.0e-12, 1.0e-10):",
"360) return (90.0, 180.0, 90.0, True) else: # side_cc is not nearly 0",
"= 1.0e-15 EpsTest = Eps * 1.001 testData = [] # test data",
"90.0, True) elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360)",
"nearly 180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180",
"side_aa is nearly zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is",
"was nearly 0. Fixed by evaluating ang_B special cases after side_aa and side_cc",
"is correct and the value of side_bb is correct to within epsilon. -",
"opscore.RO.MathUtil.cosd(ang_A * 0.5) sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA",
"90.0, True) elif side_cc < side_aa: ang_A = 180.0 side_bb = side_aa -",
"use Napier's analogy for bb - aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3,",
"abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes",
"<side_aa 180 side_aa-cc 0 any ~0 >side_aa 0 side_cc-aa 180 where: - !pole",
"abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo 360) if abs(cos_h_cc) <",
"1.001 testData = [] # test data is formatted as follows: # a",
"is near 0 or 180 (see Special Cases below for when this occurs)",
"180-side_aa 180 any ~0 ~=side_aa unknown(90) 0 unknown(90) any ~0 <side_aa 180 side_aa-cc",
"- Eps, 179.0, 47.0, Eps, 0.0): if side_aa < EpsTest: expRes = (90.0,",
"remaining quantities. Inputs: - side_aa side aa; range of sides: [0, 180] -",
"True) elif side_cc < side_aa: ang_A = 180.0 side_bb = side_aa - side_cc",
"EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (0.0, side_cc -",
"den4 = cos_h_cc * cos_h_sum_BA # compute side bb if abs (num3) +",
"print \"sin_h_cc, cos_h_cc =\",sin_h_cc, cos_h_cc # print \"sin_h_diff_aacc, sin_h_sum_aacc =\", sin_h_diff_aacc, sin_h_sum_aacc #",
"# B small, a = any not small, c = any not small:",
"Eps, 360.0): for side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0):",
"90 # expect: C = 180 - B, b = c + a",
"in (-Eps, 0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0",
"-27.0, 27.0, 0.1): for side_cc in (side_aa - 45.0, side_aa - Eps, side_aa,",
"Eps, 180.0): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 - Eps,",
"ang_A and C with side_aa=%s, ang_B=%s, side_cc=%s\" % (side_aa, ang_B, side_cc)) # compute",
"\"num1, den1, num2, den2 =\", num1, den1, num2, den2 # print \"h_sum_AC, h_diff_AC",
"ang_A if ang_C < 0: ang_C = 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc),",
"= 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb = 2.0 *",
"B for side_aa in (180.0 - Eps, 180.0, 180.0 + Eps): for ang_B",
"aa; range of sides: [0, 180] - ang_B angle b; range of angles:",
"= side_cc ang_C = 180.0 - ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa",
"= 0, A = 90, unknownAng # if a nearly 180: expect C",
"or actualOutput[2] >= 360.0: print(\"failed on input:\", testInput) print(\"one or more angles out",
"testData += [ # 90/90/90 triangle ((90, 90, 90), (90, 90, 90)), #",
"2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb to",
"C = 90, b = 0, A = 90, unknownAng # else: expect",
"cos_h_cc - cos_h_aa * sin_h_cc cos_h_sum_aacc = cos_h_aa * cos_h_cc - sin_h_aa *",
"expect C = 90, b = 180, A = 90, unknownAng # else:",
"den2 # print \"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC",
"defaults to False) # a ~ 0, B = various, c various: #",
"Returns a tuple containing: - ang_A angle a - side_bb side bb -",
"90.0, True) elif 180.0 - side_aa < EpsTest: expRes = (90.0, 0.0, 90.0,",
"sin_h_B * cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA = sin_h_B * cos_h_A -",
"0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return (",
"aa side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb =",
"side_aa and side_cc special cases. Tweaked the documentation to clarify the special cases.",
"result: ang_C, side_bb, ang_A, [unknownAng] (unknownAng defaults to False) # a ~ 0,",
"= opscore.RO.MathUtil.sind(side_cc) sin_h_B = opscore.RO.MathUtil.sind(ang_B * 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa",
"True) else: # side_cc is not nearly 0 or 180 ang_A = 0.0",
"abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0, 0.0,",
"= 180.0 + ang_C testData.append(((side_aa, ang_B, side_cc), (ang_A, side_bb, ang_C))) testData += [",
"((90, 90, 90), (90, 90, 90)), # inputs that might cause side_bb <",
"90.0, True) elif abs((side_cc - 180) % 360.0) < EpsTest: expRes = (90.0,",
"# print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa,",
"c = any not small: # if c != a: expect A =",
"(num2, den2) # print \"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa",
"h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C = h_sum_AC - h_diff_AC # +",
"compute ang_A or ang_C: return (90.0, 0.0, 90.0, True) elif side_cc < side_aa:",
"# a ~ 0, B = various, c various: # if c nearly",
"accurately determine angle = atan2 (num, den), give up if (((abs (num1) <=",
"tan c = (tan a / sinA * sinb) # with some tweaks",
"The sum of ang_A and ang_C is correct and the value of side_bb",
"- ang_B side_bb = side_aa ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: #",
"180 unknown(90) ~0 any !pole 0 side_cc 180-ang_B ~180 any ~0 unknown(90) 180",
"avoid poles # tan C = tan c / sin a # tan",
"as follows: # a list of entries, each consisting of: # - the",
"110.0, 179.0): for side_cc in (1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A =",
"- side_aa ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B is nearly",
"if numerator and denominator are too small # to accurately determine angle =",
"if abs(side_aa % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif",
"expRes)) # right triangle: B = 90, a and c vary but avoid",
"now pass. Greatly expanded the unit tests. 2010-08-04 ROwen Bug fix: mis-handled two",
"0.5) cos_h_cc = opscore.RO.MathUtil.cosd(side_cc * 0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is",
"of: # - the input argument # - the expected result: ang_C, side_bb,",
"actualOutput[2] >= 360.0: print(\"failed on input:\", testInput) print(\"one or more angles out of",
"h_diff_AC ang_C = h_sum_AC - h_diff_AC # + # compute side bb using",
"corner cases; all unit tests now pass. Greatly expanded the unit tests. 2010-08-04",
"= atan2 (num, den), give up if (((abs (num1) <= opscore.RO.SysConst.FAccuracy) and (abs",
"* cos_h_A - sin_h_B * sin_h_A cos_h_diff_BA = cos_h_B * cos_h_A + sin_h_B",
"entries, each consisting of: # - the input argument # - the expected",
"180 + Eps, 256, 359): expRes = (180.0 - ang_B, side_aa + (side_cc",
"(90.0, 180.0, 90.0, True) else: # side_cc is not nearly 0 or 180",
"case table, code and unit test were incorrect - side_aa normal + side_cc",
"cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc # compute numerator and",
"Improved accuracy in some corner cases; all unit tests now pass. Greatly expanded",
"= 180.0 + ang_A if ang_C < 0: ang_C = 180.0 + ang_C",
"unknown(90) means unknownAng is set True and the angle is unknown and is",
"a and c vary but avoid poles # tan C = tan c",
"angle c - unknownAng if true, angle A and angle C could not",
"opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\",",
"(modulo 360) return (90.0, 0.0, 90.0, True) elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc",
"C = 90, b = 180, A = 90, unknownAng # else: expect",
"b = c - a, C = 0 # if c >> a:",
"b = 0, A = 90, unknownAng # else: expect A = 180,",
"cases. Tweaked the documentation to clarify the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa)",
"45.0): if abs(side_cc - side_aa) < EpsTest: expRes = (90.0, 0.0, 90.0, True)",
"is 180, which is also essentially correct. Special Cases (in the order they",
"0 for side_cc in (0.0, Eps): for ang_B in (0.0, Eps, 32.0, 97.0,",
"- c, C = B for side_aa in (180.0 - Eps, 180.0, 180.0",
"ang_B, side_cc), expRes)) # c ~ 180, B = various, a various: #",
"elif side_cc < side_aa: ang_A = 180.0 side_bb = side_aa - side_cc ang_C",
"0.0, 90.0, True) elif abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 180.0,",
"Warnings: Allowing angles in the 3rd and 4th quadrants is unusual. References: Selby,",
"were incorrect - side_aa normal + side_cc tiny: table was right but code",
"is nearly 0 (modulo 360) return (90.0, 180.0, 90.0, True) else: # side_cc",
"side_cc), (ang_A, side_bb, ang_C))) testData += [ # 90/90/90 triangle ((90, 90, 90),",
"~180 unknown(90) 180 unknown(90) ~0 any !pole 0 side_cc 180-ang_B ~180 any ~0",
"not be computed (and are both set to 90); bb will be 0",
"90); bb will be 0 or 180 Error Conditions: - If the inputs",
"90.0, True) elif side_cc < side_aa: expRes = (180.0, side_aa - side_cc, 0.0)",
"- unknownAng if true, angle A and angle C could not be computed",
"# if a nearly 0: expect C = 90, b = 0, A",
"((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]),",
"side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb)",
"side_aa 0 !pole any ~180 ang_B 180-side_aa 180 any ~0 ~=side_aa unknown(90) 0",
"47.0, Eps, 0.0): if abs((180.0 - side_cc) % 360.0) < EpsTest: expRes =",
"expRes = (90.0, 0.0, 90.0, True) elif abs(side_cc % 360.0) < EpsTest: expRes",
"any !pole 0 side_cc 180-ang_B ~180 any ~0 unknown(90) 180 unknown(90) ~180 any",
"print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest = Eps * 1.001 testData = []",
"denominator are too small # to accurately determine angle = atan2 (num, den),",
"unknown(90) 180 unknown(90) ~0 any !pole 0 side_cc 180-ang_B ~180 any ~0 unknown(90)",
"90, a and c vary but avoid poles # tan C = tan",
"else: expect A = 0, b = a - c, C = 180",
"# compute side bb if abs (num3) + abs (den3) > abs (num4)",
"else: # side_cc is not nearly 0 or 180 ang_A = 0.0 side_bb",
"- side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__",
"in (1.0e-12, 1.0e-10): for ang_B in (23, 90, 180 - Eps, 180, 180",
"0: ang_A = 180.0 + ang_A if ang_C < 0: ang_C = 180.0",
"- Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_cc",
"any ~0 >side_aa 0 side_cc-aa 180 where: - !pole means not nearly 0",
"side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~ 180, B",
"~180 any ~0 unknown(90) 180 unknown(90) ~180 any ~180 unknown(90) 0 unknown(90) ~180",
">side_aa 0 side_cc-aa 180 where: - !pole means not nearly 0 and not",
"90, b = 180, A = 90, unknownAng # if a nearly 180",
"# a ~ 180, B = various, c various: # if c nearly",
"- side_aa) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif side_cc <",
"Eps * 1.001 testData = [] # test data is formatted as follows:",
"if abs(side_cc % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif",
"angSideAng\") Eps = 1.0e-15 EpsTest = Eps * 1.001 testData = [] #",
"side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90) ~0 any ~180 unknown(90)",
"denominator for analogy for bb - aa num3 = sin_h_cc * sin_h_diff_BA den3",
"(abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute ang_A and C with side_aa=%s,",
"360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs(side_cc % 360.0)",
"360.0 \\ or actualOutput[1] < 0.0 or actualOutput[1] >= 360.0 \\ or actualOutput[2]",
"den1, num2, den2 =\", num1, den1, num2, den2 # print \"h_sum_AC, h_diff_AC =\",",
"< 0.0 or actualOutput[0] >= 360.0 \\ or actualOutput[1] < 0.0 or actualOutput[1]",
"C ~= 0 side_aa = 90.0 for side_cc in (1.0e-12, 1.0e-10): for ang_B",
"h_diff_AC # + # compute side bb using one of two Napier's analogies",
"Error Conditions: - If the inputs are too small to allow computation, raises",
"Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0 - side_cc) % 360.0) < EpsTest:",
"near 0 or 180 (see Special Cases below for when this occurs) then",
"(side_aa, ang_B, side_cc)) # compute (a +/- c) / 2, and use to",
"15th ed, 1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng",
"= 0 for side_cc in (0.0, Eps): for ang_B in (0.0, Eps, 32.0,",
"not nearly 0 or 180 (modulo 360) ang_A = 180.0 side_bb = 180.0",
"# side_aa is nearly zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc",
"360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs((180.0 - side_aa)",
"unknown(90) 180 unknown(90) ~180 any ~180 unknown(90) 0 unknown(90) ~180 any !pole 180",
"Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_cc in",
"unknownAng if true, angle A and angle C could not be computed (and",
"unknownAng should always be true if side_aa and side_cc are nearly 0 or",
"be 180 and ang_A and ang_C unknown. Improved accuracy in some corner cases;",
"= 180.0 - side_aa ang_C = 180.0 elif abs(sin_h_B) < opscore.RO.SysConst.FAccuracy: # B",
"side_cc ang_C = ang_B elif abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero",
"<< a: expect A = 180, b = c - a, C =",
"- side_aa < EpsTest: expRes = (90.0, 0.0, 90.0, True) else: expRes =",
"small, a = any not small, c = any not small: # if",
"179.0, 47.0, Eps, 0.0): if abs(side_cc % 360.0) < EpsTest: expRes = (90.0,",
"side bb - ang_C angle c - unknownAng if true, angle A and",
"unknownAng # else: expect A = 180, b = 180 - c, C",
"C = 0 # if c >> a: expect A = 0, b",
"side_aa ang_B side_cc ang_A side_bb ang_C ---------------------------------------------------------------- ~0 any ~0 unknown(90) 0 unknown(90)",
"special cases. Tweaked the documentation to clarify the special cases. \"\"\" sin_h_aa =",
"2, and use to compute angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1,",
"A = 90, unknownAng # if c nearly 180 (modulo 360): expect C",
"zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo",
"0 or 180 ang_A = 0.0 side_bb = side_cc ang_C = 180.0 -",
"- B, b = a, C = 0 for side_cc in (0.0, Eps):",
"EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0 - ang_B,",
"= (90.0, 180.0, 90.0, True) else: expRes = (180.0 - ang_B, side_aa, 0.0)",
"side_aa tiny + side_cc normal: special case table, code and unit test were",
"180) % 360.0) < EpsTest: expRes = (90.0, 180.0, 90.0, True) else: expRes",
"- side_cc ang_C = 0.0 else: ang_A = 0.0 side_bb = side_cc -",
"True) else: expRes = (ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes))",
"if true, angle A and angle C could not be computed (and are",
"90.0, True) else: expRes = (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc),",
"\"h_sum_AC, h_diff_AC =\", h_sum_AC, h_diff_AC ang_A = h_sum_AC + h_diff_AC ang_C = h_sum_AC",
"90, unknownAng # else: expect A = 0, b = a - c,",
"True and the angle is unknown and is abitrarily set to 90 degrees.",
"~= 0 side_aa = 90.0 for side_cc in (1.0e-12, 1.0e-10): for ang_B in",
"B, b = a + c cos(B), C ~= 0 side_aa = 90.0",
"side_aa ang_C = 0.0 elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180",
"denominator for analogy for bb + aa num4 = sin_h_cc * cos_h_diff_BA den4",
"* 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc",
"zero, 360, etc. Warnings: Allowing angles in the 3rd and 4th quadrants is",
"0.5) if abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo 360) if",
"nearly 0 or 360, c fairly small but >> Eps # expect: A",
"* opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B small, a",
"expRes = (0.0, side_cc - side_aa, 180.0) for ang_B in (-Eps, 0.0, Eps):",
"all relations are modulo 360. For example ~0 means approximately zero, 360, etc.",
"testData.append(((side_aa, ang_B, side_cc), expRes)) # right triangle: B = 90, a and c",
"(1.0, 20.0, 45.0, 90, 110.0, 179.0): for side_cc in (1.0, 20.0, 45.0, 90.0,",
"to handle angles comparing things like 359.999... to 0, compare sin and cos",
"Tweaked the documentation to clarify the special cases. \"\"\" sin_h_aa = opscore.RO.MathUtil.sind(side_aa) sin_h_cc",
"# to accurately determine angle = atan2 (num, den), give up if (((abs",
"in (23, 90, 180 - Eps, 180, 180 + Eps, 256, 359): expRes",
"opscore.RO.SysConst.FAccuracy)) or ((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug:",
"where: - !pole means not nearly 0 and not nearly 180 (modulo 360)",
"(num3) + abs (den3) > abs (num4) + abs (den4): # use Napier's",
"else: expRes = (180.0, 180.0 - side_cc, ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"45), (89.6464421219342, 0.707102293688337, 89.6464421219342)), ((45, -1, 45), (270.353557878066, 0.707102293688337, 270.353557878066)), ((135, 1, 135),",
"0.0): if abs((180.0 - side_cc) % 360.0) < EpsTest: expRes = (90.0, 0.0,",
"for side_cc in (side_aa - 45.0, side_aa - Eps, side_aa, side_aa + Eps,",
"expRes = (90.0, 180.0, 90.0, True) elif 180.0 - side_aa < EpsTest: expRes",
"if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0,",
"* opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants; they're based on what works,",
"side_cc in (side_aa - 45.0, side_aa - Eps, side_aa, side_aa + Eps, side_aa",
"0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3],",
"0, compare sin and cos of ang_A and ang_C: procExpected = processOutput(expectedOutput) procActual",
"# side_cc is nearly zero (modulo 360) and side_aa is not ang_A =",
"of side_bb is correct to within epsilon. - all relations are modulo 360.",
"= 0, b = a - c, C = 180 for side_aa in",
"180] - ang_B angle b; range of angles: [0, 360) - side_cc side",
"= (0.0, side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants; they're",
"360) - side_cc side cc Returns a tuple containing: - ang_A angle a",
"360): expect C = 90, b = 180, A = 90, unknownAng #",
"side_cc in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0 -",
"(num4) + abs (den4): # use Napier's analogy for bb - aa side_bb",
"is nearly 180 (modulo 360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly",
"sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb to unknownAng; side_bb may be 180",
"180.0, 90.0, True) else: # side_cc is not nearly 0 or 180 (modulo",
"that was not happening if ang_B was nearly 0. Fixed by evaluating ang_B",
"ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # c ~ 180, B =",
"179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A)",
"(a +/- c) / 2, and use to compute angles a and c",
"== \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15 EpsTest = Eps *",
"= a - c, C = 180 - B for side_aa in (-Eps,",
"fairly small but >> Eps # expect: A = 180 - B, b",
"+ h_diff_AC ang_C = h_sum_AC - h_diff_AC # + # compute side bb",
"side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_aa %",
"- ang_B angle b; range of angles: [0, 360) - side_cc side cc",
"is not nearly 0 or 180 ang_A = 0.0 side_bb = side_cc ang_C",
"or 360, c fairly small but >> Eps # expect: A = 180",
"opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B, cos_h_B =\",",
"(1.0, 20.0, 45.0, 90.0, 110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc),",
"h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC = opscore.RO.MathUtil.atan2d (num2, den2) # print \"sin_h_B,",
"def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput,",
"or actualOutput[1] < 0.0 or actualOutput[1] >= 360.0 \\ or actualOutput[2] < 0.0",
"= (tan a / sinA * sinb) # with some tweaks to handle",
"a list of entries, each consisting of: # - the input argument #",
"of sides: [0, 180] - ang_B angle b; range of angles: [0, 360)",
"elif side_cc < side_aa: expRes = (180.0, side_aa - side_cc, 0.0) else: expRes",
"269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], )",
"expect A = 90, b = 0, C = 90, unknown # if",
"c nearly 0 (modulo 360): expect C = 90, b = 0, A",
"(90.0, 180.0, 90.0, True) else: expRes = (0.0, side_cc - side_aa, 180.0 -",
"(180.0 - Eps, 180.0, 180.0 + Eps): for ang_B in (0.0, Eps, 32.0,",
"ed, 1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted from TCC's sph_AngSideAng 1-6.",
"expRes = (90.0, 180.0, 90.0, True) else: expRes = (180.0, 180.0 - side_cc,",
"expRes = (90.0, 0.0, 90.0, True) elif abs((180.0 - side_aa) % 360.0) <",
"Eps # expect: A = 180 - B, b = a + c",
"they're based on what works, so are somewhat suspect if side_bb < 0:",
"360) ang_A = 180.0 side_bb = 180.0 - side_cc ang_C = ang_B elif",
"one of two Napier's analogies # (one is for bb - aa, one",
"(180.0, 180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs((180.0 - side_cc) %",
"c + a cos(B), A ~= 0 side_cc = 90.0 for side_aa in",
"(side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing",
"= processOutput(actualOutput) if opscore.RO.SeqUtil.matchSequences(procExpected, procActual, rtol=1.0e-10, atol=1.0e-10): print(\"failed on input:\", testInput) print(\"expected output:\",",
"side_cc), expRes)) # c ~ 0, B = various, a various: # if",
"opscore.RO.MathUtil.atan2d (num3, den3) + side_aa else: side_bb = 2.0 * opscore.RO.MathUtil.atan2d (num4, den4)",
"= sin_h_B * sin_h_sum_aacc # if numerator and denominator are too small #",
"side_cc) % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif abs(side_cc",
"else: expRes = (180.0 - ang_B, side_aa, 0.0) testData.append(((side_aa, ang_B, side_cc), expRes)) #",
"ROwen Converted from TCC's sph_AngSideAng 1-6. 2010-07-30 ROwen Changed output zero_bb to unknownAng;",
"+ Eps, 210.0, 360.0 - Eps, 360.0): for side_cc in (180.0, 180.0 -",
"side aa; range of sides: [0, 180] - ang_B angle b; range of",
"< opscore.RO.SysConst.FAccuracy: # side_cc is nearly 0 (modulo 360) return (90.0, 180.0, 90.0,",
"(0.0, side_cc + (side_aa * opscore.RO.MathUtil.cosd(ang_B)), 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes))",
"* 0.5) cos_h_B = opscore.RO.MathUtil.cosd(ang_B * 0.5) sin_h_aa = opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa",
"expRes = (90.0, 0.0, 90.0, True) else: expRes = (ang_B, 180.0 - side_aa,",
"elif abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) and side_aa",
"is unusual. References: Selby, Standard Math Tables, crc, 15th ed, 1967, p161 (Spherical",
"den4) - side_aa side_bb = opscore.RO.MathUtil.wrapPos (side_bb) return (opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if",
"= opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants; they're based",
"tweaks handle other quadrants; they're based on what works, so are somewhat suspect",
"# tan C = tan c / sin a # tan c =",
"this occurs) then angles a and c cannot be computed. In this case",
"print(\"failed on input:\", testInput) print(\"expected output:\", expectedOutput) print(\"actual output:\", actualOutput) print() if actualOutput[0]",
"for testInput, expectedOutput in testData: if len(expectedOutput) < 4: expectedOutput = expectedOutput +",
"Math Tables, crc, 15th ed, 1967, p161 (Spherical Trig.) History: 2002-07-22 ROwen Converted",
"(269.646442121934, 0.707102293688308, 269.646442121934)), ] def processOutput(outputVec): return ( opscore.RO.MathUtil.sind(outputVec[0]), opscore.RO.MathUtil.cosd(outputVec[0]), outputVec[1], opscore.RO.MathUtil.sind(outputVec[2]), opscore.RO.MathUtil.cosd(outputVec[2]),",
"!pole any ~0 180-ang_B side_aa 0 !pole any ~180 ang_B 180-side_aa 180 any",
"360) if abs(cos_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return",
"* cos_h_cc + sin_h_aa * sin_h_cc # compute numerator and denominator, where tan((a",
"not small: # if c != a: expect A = 90, b =",
"was right but code and unit test had errors 2011-01-28 ROwen Bug fix:",
"bb + aa num4 = sin_h_cc * cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA",
"= various, a various: # if a nearly 0: expect C = 90,",
"ang_C is correct and the value of side_bb is correct to within epsilon.",
"90, b = 0, A = 90, unknownAng # if c nearly 180",
"and denominator for analogy for bb + aa num4 = sin_h_cc * cos_h_diff_BA",
"opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps = 1.0e-15",
"- If side bb is near 0 or 180 (see Special Cases below",
"C = B for side_aa in (180.0 - Eps, 180.0, 180.0 + Eps):",
"90.0 for side_aa in (1.0, 20.0, 45.0, 90, 110.0, 179.0): for side_cc in",
"# expect: C = 180 - B, b = c + a cos(B),",
"side_aa < EpsTest: expRes = (90.0, 0.0, 90.0, True) else: expRes = (ang_B,",
"side_cc), expRes)) # a fairly small but >> Eps, B varies, c =",
"\"sin_h_B, cos_h_B =\", sin_h_B, cos_h_B # print \"sin_h_aa, cos_h_aa =\", sin_h_aa, cos_h_aa #",
"but not nearly 0 or 360, c fairly small but >> Eps #",
"= 0, A = 90, unknownAng # else: expect A = 180, b",
"180.0 + ang_A if ang_C < 0: ang_C = 180.0 + ang_C testData.append(((side_aa,",
"table, code and unit test were incorrect - side_aa normal + side_cc tiny:",
"- # preliminaries sin_h_A = opscore.RO.MathUtil.sind(ang_A * 0.5) cos_h_A = opscore.RO.MathUtil.cosd(ang_A * 0.5)",
"Eps, 0.0): if abs(side_aa % 360.0) < EpsTest: expRes = (90.0, 0.0, 90.0,",
"= 180, A = 90, unknownAng # else: expect A = 180, b",
"__all__ = [\"angSideAng\"] import opscore.RO.MathUtil import opscore.RO.SysConst def angSideAng(side_aa, ang_B, side_cc): \"\"\" Solves",
"and 4th quadrants is unusual. References: Selby, Standard Math Tables, crc, 15th ed,",
"for two angles and the side connecting them, given the remaining quantities. Inputs:",
"not nearly 180 (modulo 360) - unknown(90) means unknownAng is set True and",
"180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # B small, a = any",
"- side_cc) < opscore.RO.SysConst.FAccuracy: # ang_B ~= 0 (modulo 360) and side_aa ~=",
"A and angle C could not be computed (and are both set to",
"correct to within epsilon. - all relations are modulo 360. For example ~0",
"tests. 2010-08-04 ROwen Bug fix: mis-handled two cases: - side_aa tiny + side_cc",
"2010-08-04 ROwen Bug fix: mis-handled two cases: - side_aa tiny + side_cc normal:",
"side_aa) < EpsTest: expRes = (90.0, 0.0, 90.0, True) elif side_cc < side_aa:",
"is nearly zero (modulo 360) if abs(sin_h_cc) < opscore.RO.SysConst.FAccuracy: # side_cc is nearly",
"was not happening if ang_B was nearly 0. Fixed by evaluating ang_B special",
"sin_h_diff_aacc, sin_h_sum_aacc # print \"num1, den1, num2, den2 =\", num1, den1, num2, den2",
"in testData: if len(expectedOutput) < 4: expectedOutput = expectedOutput + (False,) actualOutput =",
"180 (modulo 360) ang_A = 180.0 side_bb = 180.0 - side_cc ang_C =",
"to compute angles a and c h_sum_AC = opscore.RO.MathUtil.atan2d (num1, den1) h_diff_AC =",
"expRes = (180.0 - ang_B, side_aa + (side_cc * opscore.RO.MathUtil.cosd(ang_B)), 0.0) testData.append(((side_aa, ang_B,",
"a spherical triangle for two angles and the side connecting them, given the",
"but that was not happening if ang_B was nearly 0. Fixed by evaluating",
"90, unknownAng # else: expect A = 180 - B, b = a,",
"else: # side_cc is not nearly 0 or 180 (modulo 360) ang_A =",
"for bb - aa num3 = sin_h_cc * sin_h_diff_BA den3 = cos_h_cc *",
"90 degrees. The sum of ang_A and ang_C is correct and the value",
"* sin_h_cc # compute numerator and denominator, where tan((a +/- c) / 2)",
"tuple containing: - ang_A angle a - side_bb side bb - ang_C angle",
"cc Returns a tuple containing: - ang_A angle a - side_bb side bb",
"essentially correct. Note that the sum ang_A + ang_C is 180, which is",
"Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc % 360.0) < EpsTest: expRes =",
"180.0 + Eps): for ang_B in (0.0, Eps, 32.0, 97.0, 179.0, 180.0 -",
"ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks",
"= opscore.RO.MathUtil.sind(side_aa * 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc *",
"((abs (num2) <= opscore.RO.SysConst.FAccuracy) and (abs (den2) <= opscore.RO.SysConst.FAccuracy))): raise RuntimeError(\"Bug: can't compute",
"# (one is for bb - aa, one for bb + aa) #",
"is abitrarily set to 90 degrees. The sum of ang_A and ang_C is",
"~180 any !pole 180 180-side_cc ang_B !pole any ~0 180-ang_B side_aa 0 !pole",
"180.0) for ang_B in (-Eps, 0.0, Eps): testData.append(((side_aa, ang_B, side_cc), expRes)) # right",
"A = 180 - B, b = a, C = 0 for side_cc",
"b = 0, A = 90, unknownAng # if a nearly 180: expect",
"< opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0, 0.0, 90.0,",
"# side_cc is not nearly 0 or 180 ang_A = 0.0 side_bb =",
"180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes)) # a ~ 180, B =",
"C = 90, b = 0, A = 90, unknownAng # if c",
"had errors 2011-01-28 ROwen Bug fix: unknownAng should always be true if side_aa",
"- cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A - sin_h_B * sin_h_A",
"= 90, unknownAng # if c nearly 0 (modulo 360): expect C =",
"* 0.5) sin_h_sum_BA = sin_h_B * cos_h_A + cos_h_B * sin_h_A sin_h_diff_BA =",
"output zero_bb to unknownAng; side_bb may be 180 instead of 0. Bug fix:",
"side_bb may be 180 instead of 0. Bug fix: in some cases side_bb",
"= 180, b = c - a, C = 0 # if c",
"side_aa - Eps, side_aa, side_aa + Eps, side_aa + 45.0): if abs(side_cc -",
"opscore.RO.SysConst.FAccuracy: # side_cc is nearly 180 (modulo 360) return (90.0, 0.0, 90.0, True)",
"0, B = various, a various: # if a nearly 0: expect C",
"90.0. Also side_bb = 0.0, which is essentially correct. Note that the sum",
"- Eps, 360.0): for side_aa in (180.0, 180.0 - Eps, 179.0, 47.0, Eps,",
"sin_h_B * cos_h_A - cos_h_B * sin_h_A cos_h_sum_BA = cos_h_B * cos_h_A -",
"110.0, 179.0): ang_A = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa), opscore.RO.MathUtil.sind(side_cc)) ang_C = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_cc), opscore.RO.MathUtil.sind(side_aa)) side_bb = opscore.RO.MathUtil.atan2d(opscore.RO.MathUtil.tand(side_aa),",
"Bug fix: mis-handled two cases: - side_aa tiny + side_cc normal: special case",
"- Eps, 180.0, 180.0 + Eps, 210.0, 360.0 - Eps, 360.0): for side_aa",
"if abs (num3) + abs (den3) > abs (num4) + abs (den4): #",
"ang_C = 180.0 else: # + # compute angles a and c using",
"1, 135), (90.3535578780658, 0.707102293688337, 90.3535578780658)), ((135, -1, 135), (269.646442121934, 0.707102293688308, 269.646442121934)), ] def",
"any ~180 unknown(90) 0 unknown(90) ~180 any !pole 180 180-side_cc ang_B !pole any",
"or actualOutput[2] < 0.0 or actualOutput[2] >= 360.0: print(\"failed on input:\", testInput) print(\"one",
"(ang_B, 180.0 - side_aa, 180.0) testData.append(((side_aa, ang_B, side_cc), expRes)) # a = 90,",
"180, A = 90, unknownAng # else: expect A = 180, b =",
"unknown. Improved accuracy in some corner cases; all unit tests now pass. Greatly",
"cos_h_B * cos_h_diff_aacc den1 = sin_h_B * cos_h_sum_aacc num2 = cos_h_B * sin_h_diff_aacc",
"abs (num4) + abs (den4): # use Napier's analogy for bb - aa",
"- side_aa tiny + side_cc normal: special case table, code and unit test",
"# ang_B ~= 0 (modulo 360) and side_aa ~= side_cc (modulo 360); cannot",
"or ang_C: return (90.0, 0.0, 90.0, True) elif side_cc < side_aa: ang_A =",
"- sin_h_aa * sin_h_cc cos_h_diff_aacc = cos_h_aa * cos_h_cc + sin_h_aa * sin_h_cc",
"(opscore.RO.MathUtil.wrapPos(ang_A), side_bb, opscore.RO.MathUtil.wrapPos(ang_C), False) if __name__ == \"__main__\": import opscore.RO.SeqUtil print(\"testing angSideAng\") Eps",
"B, b = c + a cos(B), A ~= 0 side_cc = 90.0",
"c = (tan a / sinA * sinb) # with some tweaks to",
"expect C = 90, b = 0, A = 90, unknownAng # if",
"opscore.RO.MathUtil.sind(ang_A) * opscore.RO.MathUtil.cosd(side_cc)) # these tweaks handle other quadrants; they're based on what",
"+ 45.0): if abs(side_cc - side_aa) < EpsTest: expRes = (90.0, 0.0, 90.0,",
"ang_B, side_cc), expRes)) # right triangle: B = 90, a and c vary",
"< opscore.RO.SysConst.FAccuracy: # side_cc is nearly zero (modulo 360) and side_aa is not",
"cause side_bb < 0, (but should not) ((45, 1, 45), (89.6464421219342, 0.707102293688337, 89.6464421219342)),",
"test data is formatted as follows: # a list of entries, each consisting",
"abs(sin_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly zero (modulo 360) if abs(sin_h_cc) <",
"special case table, code and unit test were incorrect - side_aa normal +",
"= Eps * 1.001 testData = [] # test data is formatted as",
"= sin_h_cc * cos_h_diff_BA den4 = cos_h_cc * cos_h_sum_BA # compute side bb",
"= 0 # if c >> a: expect A = 0, b =",
"opscore.RO.MathUtil.cosd(outputVec[2]), outputVec[3], ) for testInput, expectedOutput in testData: if len(expectedOutput) < 4: expectedOutput",
"expRes = (0.0, side_cc - side_aa, 180.0 - ang_B) testData.append(((side_aa, ang_B, side_cc), expRes))",
"180.0 - Eps, 179.0, 47.0, Eps, 0.0): if abs(side_cc % 360.0) < EpsTest:",
"# compute (a +/- c) / 2, and use to compute angles a",
"* 0.5) cos_h_aa = opscore.RO.MathUtil.cosd(side_aa * 0.5) sin_h_cc = opscore.RO.MathUtil.sind(side_cc * 0.5) cos_h_cc",
"- ang_B elif abs(cos_h_aa) < opscore.RO.SysConst.FAccuracy: # side_aa is nearly 180 (modulo 360)",
"if c nearly 180 (modulo 360): expect C = 90, b = 0,"
] |
[
"silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start': i + 1,",
"/ ( end - start))) for res in zip(texts, translated): logging.debug(f\" [{res[0]}] ->",
"in {pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a",
"points :param optimal_split_positions: The list of optimal split positions :type optimal_split_positions: List[float] :param",
"splits it up into sentences, translates them, and then puts them back together",
"to 2 :type pieces_count: int (optional) :return: A list of strings. \"\"\" pieces",
"(optional) :param target_language: The language to translate the text into, defaults to hu",
"translated = translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f}",
"pieces_count: int = 2) -> List[str]: \"\"\" Given a text and a number",
"translated :type texts: List[str] :param source_language: The language you want to translate from,",
"float(chars_sum) / ( end - start), float(len(texts)) / ( end - start))) for",
"* x for x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points =",
"a_general in enumerate(general): start, end, text = a_general text = text.replace('|', ' ').replace('",
"A list of strings. \"\"\" pieces = [] if pieces_count < 1: logging.error(\"pieces",
"to split the data :type where: float :param p_split_points: The list of split",
"list of split points with the optimal split point removed. \"\"\" distance_min =",
"= a_general text = text.replace('|', ' ').replace(' ', '') if len(entry['text']) > 0:",
"# ss = split_up(\"Ööö, mit csináltál?\", 3) # ss = split_up(\"Ööö, mit sdfg",
"re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index in indices_object] if 0 in possible_split_points:",
"not text.strip(): texts[i] = \" zzz \" if text.isdigit() or all(i in string.punctuation",
"logging.info(\"# Phase 1: Prepare translation: Join entries to sentences.\") for i, a_general in",
"sys.exit(1) logging.info(\"# Phase 4: Split up lines\") for i, entry in enumerate(general): pieces",
"i, entry in enumerate(general): pieces = int(len(entry[2]) / 40) + 1 if pieces",
"time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3],",
"- start))) for res in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) #",
"< distance_min: distance_min = distance min_point = a_split_point if min_point: p_split_points.remove(min_point) return min_point,",
"x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index",
"end - start, float(chars_sum) / ( end - start), float(len(texts)) / ( end",
"- start, float(chars_sum) / ( end - start), float(len(texts)) / ( end -",
"def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes a list of texts and",
"split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file,",
"\"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle = sublib.SubRip()",
"in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove(''))))",
"sentences.\") for i, a_general in enumerate(general): start, end, text = a_general text =",
"GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count: int = 2) -> List[str]:",
"out.writelines(lines) return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit",
"datetime import timedelta from pathlib import Path from typing import List import sublib",
"io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428 This is",
"sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to",
"then puts them back together :param input_file: The subtitle file to be translated",
"a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0 for split_point",
"to be translated :type texts: List[str] :param source_language: The language you want to",
"else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up lines\") for i, entry",
"or not text.strip(): texts[i] = \" zzz \" if text.isdigit() or all(i in",
"def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a list of optimal",
"' entry['text'] += text if len(general) > i + 1: start_next = general[i",
"1 if pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"#",
"- 10 or i == last_i - 1: texts = [t['text'] for t",
"output to {output_name}\") with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return lines if",
"split points and we want \" f\"to split the text '{text}' in {pieces_count}",
"result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count: int = 2)",
"= split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end =",
"if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions =",
"= text.replace('|', ' ').replace(' ', '') if len(entry['text']) > 0: entry['text'] += '",
"logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\", 3) # ss = split_up(\"Ööö, mit",
"into, defaults to hu (optional) :return: A list of translated texts. \"\"\" for",
"int (optional) :return: A list of strings. \"\"\" pieces = [] if pieces_count",
"\"\"\" for i, text in enumerate(texts): if not text or not isinstance(text, str)",
"f\"There are {len(possible_split_points)} split points and we want \" f\"to split the text",
"List[int] :return: The list of optimal split points. \"\"\" split_points = [] for",
"Phase 3: Split up sentences (undo #1)\") for i, entry in enumerate(entries_to_be_translated): text_long",
":param text: The text to split up :type text: str :param pieces_count: The",
"None for a_split_point in p_split_points: distance = abs(where - a_split_point) if distance <",
"def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle file, splits it up into",
"= 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting",
"= text[0] return first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated = [] entry",
"t in an_entry]) if chars_sum > translation_char_limit - 10 or i == last_i",
"up sentences (undo #1)\") for i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces",
"text_long = translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] + 1 texts = split_up(text=text_long,",
"auto (optional) :param target_language: The language to translate the text into, defaults to",
"entry[2] = new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines",
"list of strings. \"\"\" pieces = [] if pieces_count < 1: logging.error(\"pieces error.\")",
"range(insert_end - insert_start + 1): iii = insert_start + i2 - 1 if",
"a text and a number of pieces, split the text into pieces :param",
"= entry['index_end'] for i2 in range(insert_end - insert_start + 1): iii = insert_start",
"str :param pieces_count: The number of pieces to split the text into, defaults",
"not isinstance(text, str) or not text.strip(): texts[i] = \" zzz \" if text.isdigit()",
"index in indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 <",
"split points :param optimal_split_positions: The list of optimal split positions :type optimal_split_positions: List[float]",
"translate from, defaults to auto (optional) :param target_language: The language to translate the",
"split_points = [] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point)",
"- 1 if iii < len(general) - 1: general[iii][2] = texts[i2] else: logging.error(\"Index",
"[] if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1: return",
"from, defaults to auto (optional) :param target_language: The language to translate the text",
"of the corresponding split points :param optimal_split_positions: The list of optimal split positions",
"textwrap import time from datetime import timedelta from pathlib import Path from typing",
"requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) /",
"language to translate the text into, defaults to hu (optional) :return: A list",
"Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt')",
"an_entry]) if chars_sum > translation_char_limit - 10 or i == last_i - 1:",
"= texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up lines\") for",
"enumerate(texts): if not text or not isinstance(text, str) or not text.strip(): texts[i] =",
"> translation_char_limit - 10 or i == last_i - 1: texts = [t['text']",
"text: str :param pieces_count: The number of pieces to split the text into,",
"enumerate(general): pieces = int(len(entry[2]) / 40) + 1 if pieces > 1: new_text",
"pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\") return",
"split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end'] for i2 in range(insert_end -",
"in enumerate(texts): if not text or not isinstance(text, str) or not text.strip(): texts[i]",
"-> [{res[1]}]\") translated_all.extend(translated) # print(translated) start = i + 1 logging.info(\"# Phase 3:",
"file to be translated :param target_language: The language you want the text to",
"for index in indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1",
"= entry['index_start'] insert_end = entry['index_end'] for i2 in range(insert_end - insert_start + 1):",
"removed. \"\"\" distance_min = 9999.0 min_point = None for a_split_point in p_split_points: distance",
"= entry['index_end'] - entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) !=",
"= len(text) / pieces_count optimal_split_positions = [len_of_a_piece * x for x in range(1,",
"__name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\", 3) # ss",
"points and we want \" f\"to split the text '{text}' in {pieces_count} pieces...",
"= i + 1 logging.info(\"# Phase 3: Split up sentences (undo #1)\") for",
"defaults to hu (optional) :return: The lines of the translated file. \"\"\" translation_char_limit",
"chars_sum > translation_char_limit - 10 or i == last_i - 1: texts =",
"defaults to hu (optional) :return: A list of translated texts. \"\"\" for i,",
"text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points and we want \" f\"to split",
"+= text if len(general) > i + 1: start_next = general[i + 1][0]",
"in indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count:",
"optimal split positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points:",
"= a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text) / pieces_count",
"if distance < distance_min: distance_min = distance min_point = a_split_point if min_point: p_split_points.remove(min_point)",
"sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\", \"guten morgen\",",
"optimal_split_positions = [len_of_a_piece * x for x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+',",
"entry['text'] += text if len(general) > i + 1: start_next = general[i +",
"sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\",",
"str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\") with open(output_name, 'w', encoding='utf-8') as out:",
"possible_split_points = [index.start() for index in indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if",
"in enumerate(general): start, end, text = a_general text = text.replace('|', ' ').replace(' ',",
"timedelta from pathlib import Path from typing import List import sublib from deep_translator",
"- end if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry",
"0, 'text': ''} logging.info(\"# Phase 1: Prepare translation: Join entries to sentences.\") for",
"= {'index_start': i + 1, 'index_end': i + 1, 'text': ''} logging.info(\"# Phase",
"1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5: Saving file\")",
"re import string import sys import textwrap import time from datetime import timedelta",
"the text into pieces :param text: The text to split up :type text:",
"source_language='auto', target_language='hu'): \"\"\" It takes a list of texts and translates them from",
"# ss = split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\",",
"pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points and we",
"of the translated file. \"\"\" translation_char_limit = 4000 # 4000 subtitle = sublib.SubRip(input_file,",
"to sentences.\") for i, a_general in enumerate(general): start, end, text = a_general text",
"= get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions,",
"if pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase",
"= \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle =",
"start, float(chars_sum) / ( end - start), float(len(texts)) / ( end - start)))",
"''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes a list of texts",
"Hi there 2 00:01:04,843 --> 00:01:05,428 This is an example of a subtitle",
"List[int] :return: The optimal split point and the list of split points with",
"takes a subtitle file, splits it up into sentences, translates them, and then",
"min_point = a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text) /",
":type p_possible_split_points: List[int] :return: The list of optimal split points. \"\"\" split_points =",
"seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) / ( end -",
"sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo",
"optimal split positions, return a list of the corresponding split points :param optimal_split_positions:",
"text[0] return first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated = [] entry =",
"\"\"\" Given a list of optimal split positions, return a list of the",
"list of optimal split positions, return a list of the corresponding split points",
"target_language='hu'): \"\"\" It takes a list of texts and translates them from source",
"return [text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the optimal split point",
"want to split the data :type where: float :param p_split_points: The list of",
"of optimal split points. \"\"\" split_points = [] for an_optimal_position in optimal_split_positions: a_split_point,",
"entry['index_start'] insert_end = entry['index_end'] for i2 in range(insert_end - insert_start + 1): iii",
"req/s\".format(len(texts), end - start, float(chars_sum) / ( end - start), float(len(texts)) / (",
"defaults to auto (optional) :param target_language: The language to translate the text into,",
"3: Split up sentences (undo #1)\") for i, entry in enumerate(entries_to_be_translated): text_long =",
"1: return [text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the optimal split",
"text.isdigit() or all(i in string.punctuation for i in text): texts[i] += \" zzz",
"is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start': i",
"= [] for i in range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum =",
"= [t['text'] for t in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end =",
"entry in enumerate(general): pieces = int(len(entry[2]) / 40) + 1 if pieces >",
"translated texts. \"\"\" for i, text in enumerate(texts): if not text or not",
"split the text into, defaults to 2 :type pieces_count: int (optional) :return: A",
"The lines of the translated file. \"\"\" translation_char_limit = 4000 # 4000 subtitle",
"[] entry = {'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"# Phase 1: Prepare",
"for t in an_entry]) if chars_sum > translation_char_limit - 10 or i ==",
"import re import string import sys import textwrap import time from datetime import",
"for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}'",
"lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\", 3)",
"subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str):",
"if iii < len(general) - 1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1)",
"if chars_sum > translation_char_limit - 10 or i == last_i - 1: texts",
"text.replace('|', ' ').replace(' ', '') if len(entry['text']) > 0: entry['text'] += ' '",
"= general[i + 1][0] else: start_next = end + timedelta(100) silence_to_next = start_next",
"'.out.srt') logging.info(f\" Writing output to {output_name}\") with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines)",
"sentences (undo #1)\") for i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces =",
"start))) for res in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated)",
"import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str =",
"output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\") with open(output_name, 'w', encoding='utf-8')",
"/ ( end - start), float(len(texts)) / ( end - start))) for res",
"0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+',",
"list of optimal split points. \"\"\" split_points = [] for an_optimal_position in optimal_split_positions:",
"i == last_i - 1: texts = [t['text'] for t in entries_to_be_translated[start:i +",
"source language to target language :param texts: The list of texts to be",
"text): texts[i] += \" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def",
"overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up lines\") for i, entry in enumerate(general):",
"00:01:05,428 This is an example of a subtitle file in SRT format '''))",
"where: float :param p_split_points: The list of split points :type p_split_points: List[int] :return:",
"point and the list of split points with the optimal split point removed.",
"with the optimal split point removed. \"\"\" distance_min = 9999.0 min_point = None",
"1] chars_sum = sum([len(t['text']) for t in an_entry]) if chars_sum > translation_char_limit -",
"not text or not isinstance(text, str) or not text.strip(): texts[i] = \" zzz",
"9999.0 min_point = None for a_split_point in p_split_points: distance = abs(where - a_split_point)",
"subtitle file in SRT format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It",
"possible_split_points): \"\"\" Given a list of optimal split positions, return a list of",
"= io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428 This",
"translated_all = [] entries_to_be_translated = [] entry = {'index_start': 0, 'index_end': 0, 'text':",
"the text into, defaults to hu (optional) :return: A list of translated texts.",
"return min_point, p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions = [len_of_a_piece * x",
"pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle file, splits it up",
"copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or text.endswith('!')",
"x for x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start()",
"split point from a list of split points :param where: the point where",
"text and a number of pieces, split the text into pieces :param text:",
"if len(entry['text']) > 0: entry['text'] += ' ' entry['text'] += text if len(general)",
"pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1: return [text] def",
"text = a_general text = text.replace('|', ' ').replace(' ', '') if len(entry['text']) >",
"= [] if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1:",
"insert_end = entry['index_end'] for i2 in range(insert_end - insert_start + 1): iii =",
"i in range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for t",
"logging.error( f\"There are {len(possible_split_points)} split points and we want \" f\"to split the",
"[{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start = i + 1 logging.info(\"# Phase",
"= int(len(entry[2]) / 40) + 1 if pieces > 1: new_text = \"\\n\".join(split_up(entry[2],",
"from pathlib import Path from typing import List import sublib from deep_translator import",
"pieces :param text: The text to split up :type text: str :param pieces_count:",
"up lines\") for i, entry in enumerate(general): pieces = int(len(entry[2]) / 40) +",
"is an example of a subtitle file in SRT format ''')) def translate_array(texts:",
"= general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3]))",
"(optional) :return: The lines of the translated file. \"\"\" translation_char_limit = 4000 #",
"SRT format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes a list",
"str): return text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0]",
"entries_to_be_translated = [] entry = {'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"# Phase",
"== 1: return [text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the optimal",
"the optimal split point removed. \"\"\" distance_min = 9999.0 min_point = None for",
"1: start_next = general[i + 1][0] else: start_next = end + timedelta(100) silence_to_next",
"{:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) / ( end",
"file, splits it up into sentences, translates them, and then puts them back",
"back together :param input_file: The subtitle file to be translated :param target_language: The",
"- a_split_point) if distance < distance_min: distance_min = distance min_point = a_split_point if",
"text into pieces :param text: The text to split up :type text: str",
"get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points):",
"a_split_point in p_split_points: distance = abs(where - a_split_point) if distance < distance_min: distance_min",
"general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated",
"[t['text'] for t in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1]",
"'w', encoding='utf-8') as out: out.writelines(lines) return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) #",
"+ 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split",
"insert_start + 1): iii = insert_start + i2 - 1 if iii <",
"len(entries_to_be_translated) translated_all = [] for i in range(last_i): an_entry = entries_to_be_translated[start:i + 1]",
"up into sentences, translates them, and then puts them back together :param input_file:",
"ss = split_up(\"Ööö, mit csináltál?\", 3) # ss = split_up(\"Ööö, mit sdfg sfhg",
"entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating",
"= sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str):",
"into sentences, translates them, and then puts them back together :param input_file: The",
"start = i + 1 logging.info(\"# Phase 3: Split up sentences (undo #1)\")",
"start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\") return pieces",
"4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def",
"f\"to split the text '{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions:",
"limitation)\") start = 0 last_i = len(entries_to_be_translated) translated_all = [] for i in",
"in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] + 1 texts",
"text into, defaults to 2 :type pieces_count: int (optional) :return: A list of",
"The list of split points :type p_split_points: List[int] :return: The optimal split point",
"10 or i == last_i - 1: texts = [t['text'] for t in",
"text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha() and first_char.islower() translated_all =",
"\"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts, target_language=target_language)",
"optimal split point and the list of split points with the optimal split",
"text in enumerate(texts): if not text or not isinstance(text, str) or not text.strip():",
"positions, return a list of the corresponding split points :param optimal_split_positions: The list",
"\" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) / ( end - start), float(len(texts))",
"typing import List import sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator",
"lines\") for i, entry in enumerate(general): pieces = int(len(entry[2]) / 40) + 1",
"the point where you want to split the data :type where: float :param",
"start = 0 last_i = len(entries_to_be_translated) translated_all = [] for i in range(last_i):",
"It takes a list of texts and translates them from source language to",
"to auto (optional) :param target_language: The language to translate the text into, defaults",
"an example of a subtitle file in SRT format ''')) def translate_array(texts: List[str],",
"starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated",
"p_split_points: List[int]): \"\"\" Get the optimal split point from a list of split",
"start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip())",
"== \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\", 3) # ss =",
"zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count: int",
"string=text) possible_split_points = [index.start() for index in indices_object] if 0 in possible_split_points: possible_split_points.remove(0)",
"distance = abs(where - a_split_point) if distance < distance_min: distance_min = distance min_point",
"= GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count: int = 2) ->",
"if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1: return [text]",
"texts: The list of texts to be translated :type texts: List[str] :param source_language:",
"split point and the list of split points with the optimal split point",
"\"\"\" translation_char_limit = 4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 =",
"(optional) :return: A list of translated texts. \"\"\" for i, text in enumerate(texts):",
"pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5:",
"= new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines =",
"= copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or",
"translated_all.extend(translated) # print(translated) start = i + 1 logging.info(\"# Phase 3: Split up",
"texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up lines\") for i,",
"str) or not text.strip(): texts[i] = \" zzz \" if text.isdigit() or all(i",
"translated :param target_language: The language you want the text to be translated to,",
"str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{}",
"len(entry['text']) > 0: entry['text'] += ' ' entry['text'] += text if len(general) >",
"file in SRT format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes",
"float(len(texts)) / ( end - start))) for res in zip(texts, translated): logging.debug(f\" [{res[0]}]",
"you want to translate from, defaults to auto (optional) :param target_language: The language",
"# strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated =",
"abs(where - a_split_point) if distance < distance_min: distance_min = distance min_point = a_split_point",
"- insert_start + 1): iii = insert_start + i2 - 1 if iii",
"with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return lines if __name__ == \"__main__\":",
"deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str",
"want to translate from, defaults to auto (optional) :param target_language: The language to",
"1 if iii < len(general) - 1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\")",
"a subtitle file in SRT format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\"",
"point from a list of split points :param where: the point where you",
"example of a subtitle file in SRT format ''')) def translate_array(texts: List[str], source_language='auto',",
":type text: str :param pieces_count: The number of pieces to split the text",
"input_file: The subtitle file to be translated :param target_language: The language you want",
"pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general)",
"enumerate(general): start, end, text = a_general text = text.replace('|', ' ').replace(' ', '')",
":type texts: List[str] :param source_language: The language you want to translate from, defaults",
"are {len(possible_split_points)} split points and we want \" f\"to split the text '{text}'",
"and we want \" f\"to split the text '{text}' in {pieces_count} pieces... Giving",
"if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" |",
"the corresponding split points :param optimal_split_positions: The list of optimal split positions :type",
"a_general text = text.replace('|', ' ').replace(' ', '') if len(entry['text']) > 0: entry['text']",
"', '') if len(entry['text']) > 0: entry['text'] += ' ' entry['text'] += text",
"list of translated texts. \"\"\" for i, text in enumerate(texts): if not text",
"of optimal split positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points :type",
"iii = insert_start + i2 - 1 if iii < len(general) - 1:",
"\" if text.isdigit() or all(i in string.punctuation for i in text): texts[i] +=",
"len(text) / pieces_count optimal_split_positions = [len_of_a_piece * x for x in range(1, pieces_count)]",
"a_split_point) if distance < distance_min: distance_min = distance min_point = a_split_point if min_point:",
"# s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or",
"Path from typing import List import sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/",
"time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end -",
"2 :type pieces_count: int (optional) :return: A list of strings. \"\"\" pieces =",
"(5000 char limitation)\") start = 0 last_i = len(entries_to_be_translated) translated_all = [] for",
"{}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts, target_language=target_language) end = time.time() logging.info(",
"text or not isinstance(text, str) or not text.strip(): texts[i] = \" zzz \"",
"for i in text): texts[i] += \" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts)",
"list of split points :param where: the point where you want to split",
"2: Translate (5000 char limitation)\") start = 0 last_i = len(entries_to_be_translated) translated_all =",
"\" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count:",
"/ 40) + 1 if pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2]",
"ss = split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15)",
"p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip())",
"0: entry['text'] += ' ' entry['text'] += text if len(general) > i +",
"pieces to split the text into, defaults to 2 :type pieces_count: int (optional)",
"time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start =",
"split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in",
"> 0: entry['text'] += ' ' entry['text'] += text if len(general) > i",
"= len(entries_to_be_translated) translated_all = [] for i in range(last_i): an_entry = entries_to_be_translated[start:i +",
"\"\"\" import io import logging import re import string import sys import textwrap",
"List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a list of optimal split positions,",
"data :type where: float :param p_split_points: The list of split points :type p_split_points:",
"= translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s,",
"start, end, text = a_general text = text.replace('|', ' ').replace(' ', '') if",
"p_split_points: The list of split points :type p_split_points: List[int] :return: The optimal split",
"a list of texts and translates them from source language to target language",
"It takes a subtitle file, splits it up into sentences, translates them, and",
"List[str] :param source_language: The language you want to translate from, defaults to auto",
"').replace(' ', '') if len(entry['text']) > 0: entry['text'] += ' ' entry['text'] +=",
"( end - start), float(len(texts)) / ( end - start))) for res in",
"where you want to split the data :type where: float :param p_split_points: The",
"file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\"",
"and first_char.islower() translated_all = [] entries_to_be_translated = [] entry = {'index_start': 0, 'index_end':",
"pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'):",
"p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions = [len_of_a_piece * x for x",
"< 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1: return [text] def get_optimal_split(where:",
"to hu (optional) :return: The lines of the translated file. \"\"\" translation_char_limit =",
"entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for t in an_entry]) if chars_sum >",
"list of the corresponding split points :param optimal_split_positions: The list of optimal split",
"> 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5: Saving",
"translate the text into, defaults to hu (optional) :return: A list of translated",
"+ 1, 'index_end': i + 1, 'text': ''} logging.info(\"# Phase 2: Translate (5000",
"entry = {'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"# Phase 1: Prepare translation:",
"text if len(general) > i + 1: start_next = general[i + 1][0] else:",
"{pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\"",
"split positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int]",
"text into, defaults to hu (optional) :return: A list of translated texts. \"\"\"",
"The list of optimal split points. \"\"\" split_points = [] for an_optimal_position in",
"translated to, defaults to hu (optional) :return: The lines of the translated file.",
"> 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start': i + 1, 'index_end':",
"first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated = [] entry = {'index_start': 0,",
"= split_up(\"Ööö, mit csináltál?\", 3) # ss = split_up(\"Ööö, mit sdfg sfhg wert",
"translates them from source language to target language :param texts: The list of",
"end if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry =",
"print(translated) start = i + 1 logging.info(\"# Phase 3: Split up sentences (undo",
"{} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts, target_language=target_language) end =",
"{len(possible_split_points)} split points and we want \" f\"to split the text '{text}' in",
"pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end'] for",
"to target language :param texts: The list of texts to be translated :type",
"= translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces)",
"pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given",
"0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up",
"open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO)",
"t in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start,",
"you want the text to be translated to, defaults to hu (optional) :return:",
"import Path from typing import List import sublib from deep_translator import GoogleTranslator #",
"\"\"\" Get the optimal split point from a list of split points :param",
"possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error(",
"empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\")",
"translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s, \"",
"general[i + 1][0] else: start_next = end + timedelta(100) silence_to_next = start_next -",
"The text to split up :type text: str :param pieces_count: The number of",
"split points :param where: the point where you want to split the data",
"'text': ''} logging.info(\"# Phase 2: Translate (5000 char limitation)\") start = 0 last_i",
"sys.exit(1) elif pieces_count == 1: return [text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\"",
"text.strip(): texts[i] = \" zzz \" if text.isdigit() or all(i in string.punctuation for",
"List[int]): \"\"\" Get the optimal split point from a list of split points",
"1, 'index_end': i + 1, 'text': ''} logging.info(\"# Phase 2: Translate (5000 char",
"return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle file, splits it",
"i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] +",
"text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha()",
"pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index in indices_object] if",
"[index.start() for index in indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) +",
"sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428",
"get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the optimal split point from a list",
"strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts,",
"general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up lines\")",
"(undo #1)\") for i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end']",
"csináltál?\", 3) # ss = split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg g",
"start), float(len(texts)) / ( end - start))) for res in zip(texts, translated): logging.debug(f\"",
"a list of optimal split positions, return a list of the corresponding split",
"- 1: texts = [t['text'] for t in entries_to_be_translated[start:i + 1]] time_start =",
"point where you want to split the data :type where: float :param p_split_points:",
":param where: the point where you want to split the data :type where:",
"= 2) -> List[str]: \"\"\" Given a text and a number of pieces,",
"together :param input_file: The subtitle file to be translated :param target_language: The language",
"optimal split point removed. \"\"\" distance_min = 9999.0 min_point = None for a_split_point",
"(optional) :return: A list of strings. \"\"\" pieces = [] if pieces_count <",
"Prepare translation: Join entries to sentences.\") for i, a_general in enumerate(general): start, end,",
":type optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int] :return: The",
"time.time() translated = translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{} requests in {:.2f}",
"chars_sum = sum([len(t['text']) for t in an_entry]) if chars_sum > translation_char_limit - 10",
"split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end']",
"of a subtitle file in SRT format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'):",
"texts and translates them from source language to target language :param texts: The",
"+ 1 logging.info(\"# Phase 3: Split up sentences (undo #1)\") for i, entry",
"new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content",
"from source language to target language :param texts: The list of texts to",
"or not isinstance(text, str) or not text.strip(): texts[i] = \" zzz \" if",
"a subtitle file, splits it up into sentences, translates them, and then puts",
"= abs(where - a_split_point) if distance < distance_min: distance_min = distance min_point =",
":type p_split_points: List[int] :return: The optimal split point and the list of split",
"logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\"",
":return: The lines of the translated file. \"\"\" translation_char_limit = 4000 # 4000",
"import logging import re import string import sys import textwrap import time from",
"them, and then puts them back together :param input_file: The subtitle file to",
":return: The optimal split point and the list of split points with the",
"00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428 This is an example",
"Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843 -->",
"00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428 This is an example of a",
"pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle file,",
"= general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time()",
"= str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\") with open(output_name, 'w', encoding='utf-8') as",
"wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\", \"guten",
"def starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha() and first_char.islower() translated_all = []",
"of optimal split positions, return a list of the corresponding split points :param",
"for i, entry in enumerate(general): pieces = int(len(entry[2]) / 40) + 1 if",
"= \" zzz \" if text.isdigit() or all(i in string.punctuation for i in",
"pieces_count == 1: return [text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the",
"p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a list of optimal split positions, return",
"or i == last_i - 1: texts = [t['text'] for t in entries_to_be_translated[start:i",
"== last_i - 1: texts = [t['text'] for t in entries_to_be_translated[start:i + 1]]",
"if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start':",
"+ 1): iii = insert_start + i2 - 1 if iii < len(general)",
"for t in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] #",
"split points :type p_split_points: List[int] :return: The optimal split point and the list",
"string.punctuation for i in text): texts[i] += \" zzz \" result = GoogleTranslator(source=source_language,",
"# 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format()",
"[] entries_to_be_translated = [] entry = {'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"#",
"distance_min = distance min_point = a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece",
"= entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for t in an_entry]) if chars_sum",
"- {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts, target_language=target_language) end = time.time()",
"to {output_name}\") with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return lines if __name__",
"{'index_start': i + 1, 'index_end': i + 1, 'text': ''} logging.info(\"# Phase 2:",
"for i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end'] - entry['index_start']",
"of pieces, split the text into pieces :param text: The text to split",
"takes a list of texts and translates them from source language to target",
"i, a_general in enumerate(general): start, end, text = a_general text = text.replace('|', '",
"\"\"\" It takes a list of texts and translates them from source language",
"entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] + 1",
"\"utf-8\") # s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.')",
"4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general =",
"string import sys import textwrap import time from datetime import timedelta from pathlib",
"split the data :type where: float :param p_split_points: The list of split points",
"logging.info(\"# Phase 5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name",
"translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start = i + 1",
"texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end",
"from typing import List import sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ #",
"timedelta(100) silence_to_next = start_next - end if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end']",
"language to target language :param texts: The list of texts to be translated",
"len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)}",
"to, defaults to hu (optional) :return: The lines of the translated file. \"\"\"",
"logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start,",
":type where: float :param p_split_points: The list of split points :type p_split_points: List[int]",
":return: A list of strings. \"\"\" pieces = [] if pieces_count < 1:",
"for x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for",
"+ timedelta(100) silence_to_next = start_next - end if is_end_of_sentence(text) or silence_to_next.seconds > 1:",
"[{res[1]}]\") translated_all.extend(translated) # print(translated) start = i + 1 logging.info(\"# Phase 3: Split",
"' ' entry['text'] += text if len(general) > i + 1: start_next =",
"translation_char_limit - 10 or i == last_i - 1: texts = [t['text'] for",
"- start), float(len(texts)) / ( end - start))) for res in zip(texts, translated):",
":param p_split_points: The list of split points :type p_split_points: List[int] :return: The optimal",
"def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the optimal split point from a",
"and the list of split points with the optimal split point removed. \"\"\"",
"= empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\") with open(output_name,",
"if len(general) > i + 1: start_next = general[i + 1][0] else: start_next",
"in text): texts[i] += \" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result",
"2) -> List[str]: \"\"\" Given a text and a number of pieces, split",
"Split up sentences (undo #1)\") for i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i]",
"return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\",",
":param target_language: The language you want the text to be translated to, defaults",
"2 00:01:04,843 --> 00:01:05,428 This is an example of a subtitle file in",
"start_next = end + timedelta(100) silence_to_next = start_next - end if is_end_of_sentence(text) or",
"io import logging import re import string import sys import textwrap import time",
"split points with the optimal split point removed. \"\"\" distance_min = 9999.0 min_point",
"+ 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {}",
"range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for t in an_entry])",
"pathlib import Path from typing import List import sublib from deep_translator import GoogleTranslator",
"list of split points :type p_split_points: List[int] :return: The optimal split point and",
"to be translated :param target_language: The language you want the text to be",
"hu (optional) :return: A list of translated texts. \"\"\" for i, text in",
"\"\"\" TODO \"\"\" import io import logging import re import string import sys",
"the list of split points with the optimal split point removed. \"\"\" distance_min",
"i entries_to_be_translated.append(entry) entry = {'index_start': i + 1, 'index_end': i + 1, 'text':",
"# https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 -->",
"entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start",
"entries to sentences.\") for i, a_general in enumerate(general): start, end, text = a_general",
"--> 00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428 This is an example of",
"target_language: The language to translate the text into, defaults to hu (optional) :return:",
"logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end'] for i2 in range(insert_end - insert_start",
"[len_of_a_piece * x for x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points",
"first_char.islower() translated_all = [] entries_to_be_translated = [] entry = {'index_start': 0, 'index_end': 0,",
"\"\"\" It takes a subtitle file, splits it up into sentences, translates them,",
"in range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for t in",
"entry['index_end'] - entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces:",
"A list of translated texts. \"\"\" for i, text in enumerate(texts): if not",
"5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt',",
"pieces_count: The number of pieces to split the text into, defaults to 2",
"else: start_next = end + timedelta(100) silence_to_next = start_next - end if is_end_of_sentence(text)",
"\"\"\" pieces = [] if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count",
"end = time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts),",
"float :param p_split_points: The list of split points :type p_split_points: List[int] :return: The",
"return first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated = [] entry = {'index_start':",
"split up :type text: str :param pieces_count: The number of pieces to split",
"the text '{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points:",
"[] for i in range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text'])",
"number of pieces to split the text into, defaults to 2 :type pieces_count:",
"first_char = text[0] return first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated = []",
"to be translated to, defaults to hu (optional) :return: The lines of the",
"translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes a list of texts and translates",
"> i + 1: start_next = general[i + 1][0] else: start_next = end",
"split_pieces = entry['index_end'] - entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts)",
"dfhg g ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\", \"guten morgen\", #",
"where: the point where you want to split the data :type where: float",
"iii < len(general) - 1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"#",
"optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0 for",
"source_language: The language you want to translate from, defaults to auto (optional) :param",
"00:01:04,843 --> 00:01:05,428 This is an example of a subtitle file in SRT",
"to translate from, defaults to auto (optional) :param target_language: The language to translate",
"The subtitle file to be translated :param target_language: The language you want the",
"List[str], source_language='auto', target_language='hu'): \"\"\" It takes a list of texts and translates them",
"encoding='utf-8') as out: out.writelines(lines) return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss",
":param optimal_split_positions: The list of optimal split positions :type optimal_split_positions: List[float] :param p_possible_split_points:",
"get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces:",
"The number of pieces to split the text into, defaults to 2 :type",
"file. \"\"\" translation_char_limit = 4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2",
"text: The text to split up :type text: str :param pieces_count: The number",
"= insert_start + i2 - 1 if iii < len(general) - 1: general[iii][2]",
"= [] entries_to_be_translated = [] entry = {'index_start': 0, 'index_end': 0, 'text': ''}",
"i2 in range(insert_end - insert_start + 1): iii = insert_start + i2 -",
"The optimal split point and the list of split points with the optimal",
"error.\") sys.exit(1) elif pieces_count == 1: return [text] def get_optimal_split(where: float, p_split_points: List[int]):",
":return: A list of translated texts. \"\"\" for i, text in enumerate(texts): if",
"points with the optimal split point removed. \"\"\" distance_min = 9999.0 min_point =",
"split_points.append(a_split_point) return split_points start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind",
"import string import sys import textwrap import time from datetime import timedelta from",
"split_points start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point",
"defaults to 2 :type pieces_count: int (optional) :return: A list of strings. \"\"\"",
"p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\")",
"= possible_split_points :type p_possible_split_points: List[int] :return: The list of optimal split points. \"\"\"",
"len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end'] for i2 in",
"= 4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general",
"for res in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start",
"result def split_up(text: str, pieces_count: int = 2) -> List[str]: \"\"\" Given a",
"general = subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or text.endswith('!') def",
"i2 - 1 if iii < len(general) - 1: general[iii][2] = texts[i2] else:",
"a number of pieces, split the text into pieces :param text: The text",
"up :type text: str :param pieces_count: The number of pieces to split the",
"= {'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"# Phase 1: Prepare translation: Join",
"= Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there",
"elif pieces_count == 1: return [text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get",
"''} logging.info(\"# Phase 1: Prepare translation: Join entries to sentences.\") for i, a_general",
"for i2 in range(insert_end - insert_start + 1): iii = insert_start + i2",
"0 last_i = len(entries_to_be_translated) translated_all = [] for i in range(last_i): an_entry =",
"= start_next - end if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] = i",
"= time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end",
"= 9999.0 min_point = None for a_split_point in p_split_points: distance = abs(where -",
"of split points with the optimal split point removed. \"\"\" distance_min = 9999.0",
"logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start = time.time() translated = translate_array(texts=texts, target_language=target_language) end",
"in {pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points):",
"'') if len(entry['text']) > 0: entry['text'] += ' ' entry['text'] += text if",
"( end - start))) for res in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\")",
"from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt')",
"points :param where: the point where you want to split the data :type",
"TODO \"\"\" import io import logging import re import string import sys import",
"return split_points start_ind = 0 for split_point in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind =",
"= [] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return",
"= sum([len(t['text']) for t in an_entry]) if chars_sum > translation_char_limit - 10 or",
"new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text logging.info(\"# Phase 5: Saving file\") empty_subtitle",
"end, text = a_general text = text.replace('|', ' ').replace(' ', '') if len(entry['text'])",
"target_language: The language you want the text to be translated to, defaults to",
"import io import logging import re import string import sys import textwrap import",
"the text to be translated to, defaults to hu (optional) :return: The lines",
"p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0 for split_point in",
"= i entries_to_be_translated.append(entry) entry = {'index_start': i + 1, 'index_end': i + 1,",
"logging.info(f\" Writing output to {output_name}\") with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return",
"in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start = i",
"split the text '{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float],",
"sentences, translates them, and then puts them back together :param input_file: The subtitle",
"of pieces to split the text into, defaults to 2 :type pieces_count: int",
"sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a list of",
"subtitle file, splits it up into sentences, translates them, and then puts them",
"1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} -",
"in range(insert_end - insert_start + 1): iii = insert_start + i2 - 1",
"'{text}' in {pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes",
"Join entries to sentences.\") for i, a_general in enumerate(general): start, end, text =",
"split_up(\"Ööö, mit csináltál?\", 3) # ss = split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg",
"want \" f\"to split the text '{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42)",
"for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind",
"ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\", \"guten morgen\", # 'Weltfrieden für",
"texts: List[str] :param source_language: The language you want to translate from, defaults to",
"start_next = general[i + 1][0] else: start_next = end + timedelta(100) silence_to_next =",
"them from source language to target language :param texts: The list of texts",
"+ 1: start_next = general[i + 1][0] else: start_next = end + timedelta(100)",
"you want to split the data :type where: float :param p_split_points: The list",
"i + 1, 'index_end': i + 1, 'text': ''} logging.info(\"# Phase 2: Translate",
"if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are",
"subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text:",
"entries_to_be_translated.append(entry) entry = {'index_start': i + 1, 'index_end': i + 1, 'text': ''}",
"puts them back together :param input_file: The subtitle file to be translated :param",
"general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\") logging.info(\"Translating {} - {}\".format(str(time_start)[:-3], str(time_end)[:-3])) start",
"insert_start = entry['index_start'] insert_end = entry['index_end'] for i2 in range(insert_end - insert_start +",
"= re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index in indices_object] if 0 in",
"'{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] =",
"[] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points",
"be translated :param target_language: The language you want the text to be translated",
"entry = {'index_start': i + 1, 'index_end': i + 1, 'text': ''} logging.info(\"#",
"a list of the corresponding split points :param optimal_split_positions: The list of optimal",
"the data :type where: float :param p_split_points: The list of split points :type",
"= distance min_point = a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece =",
"to split up :type text: str :param pieces_count: The number of pieces to",
"\"\"\" split_points = [] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points)",
"translation_char_limit = 4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle)",
"for i in range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for",
"The list of texts to be translated :type texts: List[str] :param source_language: The",
"pieces = int(len(entry[2]) / 40) + 1 if pieces > 1: new_text =",
"mit sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) # result =",
"entry['index_end'] for i2 in range(insert_end - insert_start + 1): iii = insert_start +",
"15) # result = translate_array(texts=[\"hallo welt\", \"guten morgen\", # 'Weltfrieden für Manuela'], target_language='hu')",
"start_next - end if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry)",
"= [len_of_a_piece * x for x in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text)",
"Translate (5000 char limitation)\") start = 0 last_i = len(entries_to_be_translated) translated_all = []",
"+ 1, 'text': ''} logging.info(\"# Phase 2: Translate (5000 char limitation)\") start =",
"1, 'text': ''} logging.info(\"# Phase 2: Translate (5000 char limitation)\") start = 0",
"we want \" f\"to split the text '{text}' in {pieces_count} pieces... Giving up.\")",
"- 1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split",
"\"\"\" distance_min = 9999.0 min_point = None for a_split_point in p_split_points: distance =",
"target_language=target_language) end = time.time() logging.info( \"{} requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f}",
"language :param texts: The list of texts to be translated :type texts: List[str]",
"number of pieces, split the text into pieces :param text: The text to",
"GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\",
"of split points :type p_split_points: List[int] :return: The optimal split point and the",
"sublib.SubRip(input_file, \"utf-8\") # s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str): return",
"1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1: return [text] def get_optimal_split(where: float,",
"to split the text into, defaults to 2 :type pieces_count: int (optional) :return:",
"logging.info(\"# Phase 3: Split up sentences (undo #1)\") for i, entry in enumerate(entries_to_be_translated):",
"< len(general) - 1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase",
"import time from datetime import timedelta from pathlib import Path from typing import",
"+ i2 - 1 if iii < len(general) - 1: general[iii][2] = texts[i2]",
"return a list of the corresponding split points :param optimal_split_positions: The list of",
"text to be translated to, defaults to hu (optional) :return: The lines of",
"lines of the translated file. \"\"\" translation_char_limit = 4000 # 4000 subtitle =",
"''} logging.info(\"# Phase 2: Translate (5000 char limitation)\") start = 0 last_i =",
"insert_start + i2 - 1 if iii < len(general) - 1: general[iii][2] =",
"list of optimal split positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points",
"'index_end': 0, 'text': ''} logging.info(\"# Phase 1: Prepare translation: Join entries to sentences.\")",
"pieces, split the text into pieces :param text: The text to split up",
"# https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1",
"This is an example of a subtitle file in SRT format ''')) def",
"p_split_points: distance = abs(where - a_split_point) if distance < distance_min: distance_min = distance",
"and translates them from source language to target language :param texts: The list",
"= [] entry = {'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"# Phase 1:",
":param texts: The list of texts to be translated :type texts: List[str] :param",
"zzz \" if text.isdigit() or all(i in string.punctuation for i in text): texts[i]",
"p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int] :return: The list of optimal split",
"empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing",
"in SRT format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes a",
"positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int] :return:",
"the text into, defaults to 2 :type pieces_count: int (optional) :return: A list",
"min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions = [len_of_a_piece",
"= end + timedelta(100) silence_to_next = start_next - end if is_end_of_sentence(text) or silence_to_next.seconds",
"1: texts = [t['text'] for t in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1]",
"1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up",
"target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count: int = 2) -> List[str]: \"\"\"",
"in string.punctuation for i in text): texts[i] += \" zzz \" result =",
"up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a list",
"if text.isdigit() or all(i in string.punctuation for i in text): texts[i] += \"",
"or silence_to_next.seconds > 1: entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start': i +",
"str, pieces_count: int = 2) -> List[str]: \"\"\" Given a text and a",
"empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\") with open(output_name, 'w',",
"sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi",
"to hu (optional) :return: A list of translated texts. \"\"\" for i, text",
"csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\", \"guten morgen\", # 'Weltfrieden für Manuela'],",
"entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start': i + 1, 'index_end': i +",
"g ghdfhg csináltál?\", 15) # result = translate_array(texts=[\"hallo welt\", \"guten morgen\", # 'Weltfrieden",
"import timedelta from pathlib import Path from typing import List import sublib from",
"last_i = len(entries_to_be_translated) translated_all = [] for i in range(last_i): an_entry = entries_to_be_translated[start:i",
"{pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle",
"https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456",
"i, text in enumerate(texts): if not text or not isinstance(text, str) or not",
"return text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0] return",
"Given a text and a number of pieces, split the text into pieces",
"= sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output",
"strings. \"\"\" pieces = [] if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif",
"from a list of split points :param where: the point where you want",
"is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char =",
"| \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points and we want \"",
"subtitle file to be translated :param target_language: The language you want the text",
"\".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points and we want \" f\"to",
"The language you want the text to be translated to, defaults to hu",
"#1)\") for i, entry in enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end'] -",
"1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start']",
"hu (optional) :return: The lines of the translated file. \"\"\" translation_char_limit = 4000",
"of split points :param where: the point where you want to split the",
"logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points and we want",
"= possible_split_points): \"\"\" Given a list of optimal split positions, return a list",
"pieces_count optimal_split_positions = [len_of_a_piece * x for x in range(1, pieces_count)] indices_object =",
"+ 1] chars_sum = sum([len(t['text']) for t in an_entry]) if chars_sum > translation_char_limit",
"- entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\")",
"all(i in string.punctuation for i in text): texts[i] += \" zzz \" result",
"split point removed. \"\"\" distance_min = 9999.0 min_point = None for a_split_point in",
"import sys import textwrap import time from datetime import timedelta from pathlib import",
"Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a",
"1 00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843 --> 00:01:05,428 This is an",
"in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) / (",
"a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions",
":param source_language: The language you want to translate from, defaults to auto (optional)",
"end - start), float(len(texts)) / ( end - start))) for res in zip(texts,",
"The list of optimal split positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int] =",
"of translated texts. \"\"\" for i, text in enumerate(texts): if not text or",
"language you want to translate from, defaults to auto (optional) :param target_language: The",
"Phase 2: Translate (5000 char limitation)\") start = 0 last_i = len(entries_to_be_translated) translated_all",
"Get the optimal split point from a list of split points :param where:",
"len(general) - 1: general[iii][2] = texts[i2] else: logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4:",
"translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] + 1 texts = split_up(text=text_long, pieces_count=split_pieces) if",
"'index_end': i + 1, 'text': ''} logging.info(\"# Phase 2: Translate (5000 char limitation)\")",
"distance_min: distance_min = distance min_point = a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points",
"text to split up :type text: str :param pieces_count: The number of pieces",
"1: entry['index_end'] = i entries_to_be_translated.append(entry) entry = {'index_start': i + 1, 'index_end': i",
"char limitation)\") start = 0 last_i = len(entries_to_be_translated) translated_all = [] for i",
"logging.info(\"# Phase 2: Translate (5000 char limitation)\") start = 0 last_i = len(entries_to_be_translated)",
"logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start = i + 1 logging.info(\"#",
"logging.info(\"# Phase 4: Split up lines\") for i, entry in enumerate(general): pieces =",
"or text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha() and first_char.islower() translated_all",
"range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index in indices_object]",
"in an_entry]) if chars_sum > translation_char_limit - 10 or i == last_i -",
"enumerate(entries_to_be_translated): text_long = translated_all[i] split_pieces = entry['index_end'] - entry['index_start'] + 1 texts =",
"List[int] = possible_split_points): \"\"\" Given a list of optimal split positions, return a",
"translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle file, splits it up into sentences,",
"indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index in indices_object] if 0",
"--> 00:01:05,428 This is an example of a subtitle file in SRT format",
"of texts to be translated :type texts: List[str] :param source_language: The language you",
"of strings. \"\"\" pieces = [] if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1)",
"split the text into pieces :param text: The text to split up :type",
"for i, text in enumerate(texts): if not text or not isinstance(text, str) or",
"sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() /",
"int = 2) -> List[str]: \"\"\" Given a text and a number of",
"min_point = None for a_split_point in p_split_points: distance = abs(where - a_split_point) if",
"texts to be translated :type texts: List[str] :param source_language: The language you want",
"corresponding split points :param optimal_split_positions: The list of optimal split positions :type optimal_split_positions:",
"' ').replace(' ', '') if len(entry['text']) > 0: entry['text'] += ' ' entry['text']",
"\"\"\" Given a text and a number of pieces, split the text into",
"\" zzz \" if text.isdigit() or all(i in string.punctuation for i in text):",
"be translated :type texts: List[str] :param source_language: The language you want to translate",
"texts[i] = \" zzz \" if text.isdigit() or all(i in string.punctuation for i",
":param target_language: The language to translate the text into, defaults to hu (optional)",
"or all(i in string.punctuation for i in text): texts[i] += \" zzz \"",
"to translate the text into, defaults to hu (optional) :return: A list of",
":param input_file: The subtitle file to be translated :param target_language: The language you",
"< pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points and",
"import textwrap import time from datetime import timedelta from pathlib import Path from",
"= time.time() translated = translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{} requests in",
"Writing output to {output_name}\") with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return lines",
"p_split_points: List[int] :return: The optimal split point and the list of split points",
"= subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text:",
"as out: out.writelines(lines) return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss =",
"import List import sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file",
"def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char",
"logging import re import string import sys import textwrap import time from datetime",
"'text': ''} logging.info(\"# Phase 1: Prepare translation: Join entries to sentences.\") for i,",
"i in text): texts[i] += \" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return",
"text = text.replace('|', ' ').replace(' ', '') if len(entry['text']) > 0: entry['text'] +=",
"get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int] = possible_split_points): \"\"\" Given a list of optimal split",
"in enumerate(general): pieces = int(len(entry[2]) / 40) + 1 if pieces > 1:",
":param pieces_count: The number of pieces to split the text into, defaults to",
"List[float] :param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int] :return: The list of",
"split points. \"\"\" split_points = [] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points =",
"end + timedelta(100) silence_to_next = start_next - end if is_end_of_sentence(text) or silence_to_next.seconds >",
"points :type p_split_points: List[int] :return: The optimal split point and the list of",
"1): iii = insert_start + i2 - 1 if iii < len(general) -",
"format ''')) def translate_array(texts: List[str], source_language='auto', target_language='hu'): \"\"\" It takes a list of",
"from datetime import timedelta from pathlib import Path from typing import List import",
"translates them, and then puts them back together :param input_file: The subtitle file",
"text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha() and first_char.islower()",
"start = time.time() translated = translate_array(texts=texts, target_language=target_language) end = time.time() logging.info( \"{} requests",
"The language to translate the text into, defaults to hu (optional) :return: A",
"target_language='hu'): \"\"\" It takes a subtitle file, splits it up into sentences, translates",
"\"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) / ( end - start), float(len(texts)) /",
"isinstance(text, str) or not text.strip(): texts[i] = \" zzz \" if text.isdigit() or",
"/ Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there 2 00:01:04,843",
"str): first_char = text[0] return first_char.isalpha() and first_char.islower() translated_all = [] entries_to_be_translated =",
"text '{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42) def get_split_points(optimal_split_positions: List[float], p_possible_split_points: List[int]",
"float, p_split_points: List[int]): \"\"\" Get the optimal split point from a list of",
"sys import textwrap import time from datetime import timedelta from pathlib import Path",
"lines = empty_subtitle.content output_name = str(input_file).replace('.srt', '.out.srt') logging.info(f\" Writing output to {output_name}\") with",
"possible_split_points :type p_possible_split_points: List[int] :return: The list of optimal split points. \"\"\" split_points",
"List[str]: \"\"\" Given a text and a number of pieces, split the text",
"List[int] = possible_split_points :type p_possible_split_points: List[int] :return: The list of optimal split points.",
"res in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start =",
"# print(translated) start = i + 1 logging.info(\"# Phase 3: Split up sentences",
"of texts and translates them from source language to target language :param texts:",
"split positions, return a list of the corresponding split points :param optimal_split_positions: The",
"[text] def get_optimal_split(where: float, p_split_points: List[int]): \"\"\" Get the optimal split point from",
"a list of split points :param where: the point where you want to",
"optimal_split_positions: The list of optimal split positions :type optimal_split_positions: List[float] :param p_possible_split_points: List[int]",
"if not text or not isinstance(text, str) or not text.strip(): texts[i] = \"",
"in range(1, pieces_count)] indices_object = re.finditer(pattern=r'\\w+', string=text) possible_split_points = [index.start() for index in",
"in get_split_points(optimal_split_positions=optimal_split_positions, p_possible_split_points=possible_split_points): pieces.append(text[start_ind:split_point].strip()) start_ind = split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count}",
"them back together :param input_file: The subtitle file to be translated :param target_language:",
"= split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) #",
"distance < distance_min: distance_min = distance min_point = a_split_point if min_point: p_split_points.remove(min_point) return",
"{output_name}\") with open(output_name, 'w', encoding='utf-8') as out: out.writelines(lines) return lines if __name__ ==",
"i + 1 logging.info(\"# Phase 3: Split up sentences (undo #1)\") for i,",
"target language :param texts: The list of texts to be translated :type texts:",
"the translated file. \"\"\" translation_char_limit = 4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\")",
"1][0] else: start_next = end + timedelta(100) silence_to_next = start_next - end if",
"texts = [t['text'] for t in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end",
"= [index.start() for index in indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points)",
"Split up lines\") for i, entry in enumerate(general): pieces = int(len(entry[2]) / 40)",
"+ 1][0] else: start_next = end + timedelta(100) silence_to_next = start_next - end",
"time from datetime import timedelta from pathlib import Path from typing import List",
"point removed. \"\"\" distance_min = 9999.0 min_point = None for a_split_point in p_split_points:",
"into, defaults to 2 :type pieces_count: int (optional) :return: A list of strings.",
"1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There are {len(possible_split_points)} split points",
"or text.endswith('?') or text.endswith('!') def starts_with_lowercase(text: str): first_char = text[0] return first_char.isalpha() and",
"return result def split_up(text: str, pieces_count: int = 2) -> List[str]: \"\"\" Given",
"texts. \"\"\" for i, text in enumerate(texts): if not text or not isinstance(text,",
"def split_up(text: str, pieces_count: int = 2) -> List[str]: \"\"\" Given a text",
"s2 = copy.deepcopy(subtitle) general = subtitle.get_general_format() def is_end_of_sentence(text: str): return text.endswith('.') or text.endswith('?')",
"i + 1, 'text': ''} logging.info(\"# Phase 2: Translate (5000 char limitation)\") start",
"3) # ss = split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg",
"the optimal split point from a list of split points :param where: the",
"want the text to be translated to, defaults to hu (optional) :return: The",
"+= ' ' entry['text'] += text if len(general) > i + 1: start_next",
"for i, a_general in enumerate(general): start, end, text = a_general text = text.replace('|',",
"1 logging.info(\"# Phase 3: Split up sentences (undo #1)\") for i, entry in",
"distance_min = 9999.0 min_point = None for a_split_point in p_split_points: distance = abs(where",
"optimal_split_positions: List[float] :param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int] :return: The list",
"zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated) # print(translated) start = i +",
"{pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It takes a subtitle file, splits",
"min_point, p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions = [len_of_a_piece * x for",
"silence_to_next = start_next - end if is_end_of_sentence(text) or silence_to_next.seconds > 1: entry['index_end'] =",
"+ 1 if pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] = new_text",
"The language you want to translate from, defaults to auto (optional) :param target_language:",
"1: Prepare translation: Join entries to sentences.\") for i, a_general in enumerate(general): start,",
"if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\", 3) #",
"list of texts to be translated :type texts: List[str] :param source_language: The language",
"pieces_count: int (optional) :return: A list of strings. \"\"\" pieces = [] if",
":type pieces_count: int (optional) :return: A list of strings. \"\"\" pieces = []",
"into pieces :param text: The text to split up :type text: str :param",
"for a_split_point in p_split_points: distance = abs(where - a_split_point) if distance < distance_min:",
"Given a list of optimal split positions, return a list of the corresponding",
"+ 1 texts = split_up(text=text_long, pieces_count=split_pieces) if len(texts) != split_pieces: logging.error(\"bahh\") insert_start =",
"out: out.writelines(lines) return lines if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö,",
"an_entry = entries_to_be_translated[start:i + 1] chars_sum = sum([len(t['text']) for t in an_entry]) if",
"int(len(entry[2]) / 40) + 1 if pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces))",
"= None for a_split_point in p_split_points: distance = abs(where - a_split_point) if distance",
"last_i - 1: texts = [t['text'] for t in entries_to_be_translated[start:i + 1]] time_start",
"p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text) / pieces_count optimal_split_positions = [len_of_a_piece *",
"distance min_point = a_split_point if min_point: p_split_points.remove(min_point) return min_point, p_split_points len_of_a_piece = len(text)",
"logging.error(\"Index overrun.\") sys.exit(1) logging.info(\"# Phase 4: Split up lines\") for i, entry in",
"and then puts them back together :param input_file: The subtitle file to be",
"in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind = 0",
"Phase 5: Saving file\") empty_subtitle = sublib.SubRip() empty_subtitle.set_from_general_format(general) lines = empty_subtitle.content output_name =",
"if len(texts) != split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end'] for i2",
"0, 'index_end': 0, 'text': ''} logging.info(\"# Phase 1: Prepare translation: Join entries to",
"up '{text}' in {pieces_count} pieces: {pieces}\") return pieces def translate_subtitle_file(input_file=sample_file, target_language='hu'): \"\"\" It",
":param p_possible_split_points: List[int] = possible_split_points :type p_possible_split_points: List[int] :return: The list of optimal",
"https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123",
"\" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str, pieces_count: int =",
"an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position, p_split_points=p_possible_split_points) split_points.append(a_split_point) return split_points start_ind =",
"be translated to, defaults to hu (optional) :return: The lines of the translated",
"sum([len(t['text']) for t in an_entry]) if chars_sum > translation_char_limit - 10 or i",
"4: Split up lines\") for i, entry in enumerate(general): pieces = int(len(entry[2]) /",
"+= \" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text: str,",
"points. \"\"\" split_points = [] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points = get_optimal_split(where=an_optimal_position,",
"Path(__file__).parent.parent.parent.absolute() / Path('input/1_short.srt') sample_str = io.StringIO(textwrap.dedent('''\\ 1 00:00:00,123 --> 00:00:03,456 Hi there 2",
"len_of_a_piece = len(text) / pieces_count optimal_split_positions = [len_of_a_piece * x for x in",
"!= split_pieces: logging.error(\"bahh\") insert_start = entry['index_start'] insert_end = entry['index_end'] for i2 in range(insert_end",
"List import sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file =",
"mit csináltál?\", 3) # ss = split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg",
"in entries_to_be_translated[start:i + 1]] time_start = general[entries_to_be_translated[start]['index_end']][1] time_end = general[entries_to_be_translated[i]['index_end']][1] # strfdelta(time_start, \"{hours}:{minutes}:{seconds}\")",
"i + 1: start_next = general[i + 1][0] else: start_next = end +",
"texts[i] += \" zzz \" result = GoogleTranslator(source=source_language, target=target_language).translate_batch(texts) return result def split_up(text:",
":return: The list of optimal split points. \"\"\" split_points = [] for an_optimal_position",
"import sublib from deep_translator import GoogleTranslator # https://pypi.org/project/sublib/ # https://pypi.org/project/deep-translator sample_file = Path(__file__).parent.parent.parent.absolute()",
"split_up(text: str, pieces_count: int = 2) -> List[str]: \"\"\" Given a text and",
"len(general) > i + 1: start_next = general[i + 1][0] else: start_next =",
"\" f\"to split the text '{text}' in {pieces_count} pieces... Giving up.\") sys.exit(42) def",
"optimal split point from a list of split points :param where: the point",
"ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum) / ( end - start),",
"# result = translate_array(texts=[\"hallo welt\", \"guten morgen\", # 'Weltfrieden für Manuela'], target_language='hu') translate_subtitle_file(input_file=sample_file)",
"there 2 00:01:04,843 --> 00:01:05,428 This is an example of a subtitle file",
"list of texts and translates them from source language to target language :param",
"it up into sentences, translates them, and then puts them back together :param",
"Phase 4: Split up lines\") for i, entry in enumerate(general): pieces = int(len(entry[2])",
"40) + 1 if pieces > 1: new_text = \"\\n\".join(split_up(entry[2], pieces_count=pieces)) entry[2] =",
"/ pieces_count optimal_split_positions = [len_of_a_piece * x for x in range(1, pieces_count)] indices_object",
"in p_split_points: distance = abs(where - a_split_point) if distance < distance_min: distance_min =",
"= split_point pieces.append(text[start_ind:].strip()) logging.debug(f\"Splitting up '{text}' in {pieces_count} pieces: {pieces}\") return pieces def",
"optimal split points. \"\"\" split_points = [] for an_optimal_position in optimal_split_positions: a_split_point, p_possible_split_points",
"{'index_start': 0, 'index_end': 0, 'text': ''} logging.info(\"# Phase 1: Prepare translation: Join entries",
"Phase 1: Prepare translation: Join entries to sentences.\") for i, a_general in enumerate(general):",
"language you want the text to be translated to, defaults to hu (optional)",
"and a number of pieces, split the text into pieces :param text: The",
"= 0 last_i = len(entries_to_be_translated) translated_all = [] for i in range(last_i): an_entry",
"pieces = [] if pieces_count < 1: logging.error(\"pieces error.\") sys.exit(1) elif pieces_count ==",
"logging.error(\"pieces error.\") sys.exit(1) elif pieces_count == 1: return [text] def get_optimal_split(where: float, p_split_points:",
"translated file. \"\"\" translation_char_limit = 4000 # 4000 subtitle = sublib.SubRip(input_file, \"utf-8\") #",
"\"{} requests in {:.2f} seconds,{:.0f} ch/s, \" \"{:.2f} req/s\".format(len(texts), end - start, float(chars_sum)",
"split_up(\"Ööö, mit sdfg sfhg wert sxghsfhgdfhg dfhg g ghdfhg csináltál?\", 15) # result",
"translated_all = [] for i in range(last_i): an_entry = entries_to_be_translated[start:i + 1] chars_sum",
"entry['text'] += ' ' entry['text'] += text if len(general) > i + 1:",
"\"__main__\": logging.basicConfig(level=logging.INFO) # ss = split_up(\"Ööö, mit csináltál?\", 3) # ss = split_up(\"Ööö,",
"possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\" | \".join(re.split(r'\\W+', text).remove('')))) logging.error( f\"There",
"indices_object] if 0 in possible_split_points: possible_split_points.remove(0) if len(possible_split_points) + 1 < pieces_count: logging.info(\"[{}]\".format(\"",
"p_possible_split_points: List[int] :return: The list of optimal split points. \"\"\" split_points = []",
"end - start))) for res in zip(texts, translated): logging.debug(f\" [{res[0]}] -> [{res[1]}]\") translated_all.extend(translated)",
"translation: Join entries to sentences.\") for i, a_general in enumerate(general): start, end, text",
"-> List[str]: \"\"\" Given a text and a number of pieces, split the"
] |
[
"def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in as {bot.user}",
"_foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID:",
"os from src.ezcord import * APP = 874663148374880287 TEST = 877399405056102431 bot =",
"def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx:",
"APP = 874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping')",
"Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**')",
"await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID: {bot.user.id})') print(f'------')",
"@bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in",
"874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def",
"import * APP = 874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST,",
"Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await",
"await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready():",
"async def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def",
"877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd",
"{bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def",
"app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await",
"= 874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async",
"ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context):",
"TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx:",
"Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID: {bot.user.id})')",
"Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async",
"bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd =",
"emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}')",
"= Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event",
"from src.ezcord import * APP = 874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-',",
"= 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context):",
"ctx.reply(embed=emd) @bot.command(name='foo') async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged",
"ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID: {bot.user.id})') print(f'------') bot.run(os.getenv('DISCORD_TOKEN'))",
"src.ezcord import * APP = 874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP,",
"guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd)",
"@bot.command(name='ping') async def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo') async",
"import os from src.ezcord import * APP = 874663148374880287 TEST = 877399405056102431 bot",
"intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd = Embed(description=f'**Pong: {bot.latency}ms**') await ctx.reply(embed=emd) @bot.command(name='foo')",
"= Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members) @bot.command(name='ping') async def ping(ctx: Context): emd = Embed(description=f'**Pong:",
"async def _foo(ctx: Context): await ctx.send(f'{bot.user()}') @bot.event async def on_ready(): print(f'Logged in as",
"* APP = 874663148374880287 TEST = 877399405056102431 bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members)"
] |
[
"from kaiba.models.kaiba_object import KaibaObject def test_create_jsonschema_from_model(): \"\"\"Test that we can create jsonschema.\"\"\" assert",
"kaiba.models.kaiba_object import KaibaObject def test_create_jsonschema_from_model(): \"\"\"Test that we can create jsonschema.\"\"\" assert KaibaObject.schema_json(indent=2)"
] |
[
"{'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data = '{",
"default key \"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY':",
"FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning was logged",
"m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file was read self.assertTrue(",
"either: 1) environment 2) file 3) or fallbacks on default key \"\"\" expected_key",
"\\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file was",
"{'mode': 'r'}) # 3) or fallbacks on default key with mock.patch('builtins.open') as m_open,",
"'r'}) # 3) or fallbacks on default key with mock.patch('builtins.open') as m_open, \\",
"get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data = '{ \"key\" : \"%s\" }'",
"actual_key) # verifies the fallback warning was logged self.assertTrue( 'Cannot get Etherscan API",
"\"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key()",
"get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1],",
"actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith(",
"2) file read_data = '{ \"key\" : \"%s\" }' % (expected_key) with mock.patch('builtins.open',",
"retrieved from either: 1) environment 2) file 3) or fallbacks on default key",
"unittest from unittest import mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self):",
"\"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key",
"(expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) #",
": \"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key =",
"actual_key) # verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'})",
"get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning was logged self.assertTrue( 'Cannot get",
"be retrieved from either: 1) environment 2) file 3) or fallbacks on default",
"pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key can be",
"verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3)",
"= FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning was",
"# 3) or fallbacks on default key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger')",
"# verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) #",
"= get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json'))",
"test_get_etherscan_api_key(self): \"\"\" Verifies the key can be retrieved from either: 1) environment 2)",
"fallbacks on default key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect",
"3) or fallbacks on default key \"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment",
"# 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key)",
"or fallbacks on default key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger:",
"% (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key)",
"file 3) or fallbacks on default key \"\"\" expected_key = '0102030405060708091011121314151617' # 1)",
"mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file",
"class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key can be retrieved from either:",
"the key can be retrieved from either: 1) environment 2) file 3) or",
"m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback",
"key can be retrieved from either: 1) environment 2) file 3) or fallbacks",
"environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2)",
"'{ \"key\" : \"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open:",
"on default key \"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ',",
"m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key)",
"'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data =",
"with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file",
"expected_key) # 2) file read_data = '{ \"key\" : \"%s\" }' % (expected_key)",
"as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the file was read",
"\"\"\" Verifies the key can be retrieved from either: 1) environment 2) file",
"3) or fallbacks on default key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as",
"TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key can be retrieved from either: 1)",
"'0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key,",
"fallbacks on default key \"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment with mock.patch.dict(",
"default key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError",
"read_data = '{ \"key\" : \"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\",
"the fallback warning was logged self.assertTrue( 'Cannot get Etherscan API key.' in m_logger.warning.call_args_list[0][0][0])",
"self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning was logged self.assertTrue( 'Cannot get Etherscan",
"'/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks on default key with mock.patch('builtins.open')",
"mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key()",
"import unittest from unittest import mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def",
"= '0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key()",
"actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data = '{ \"key\" :",
"self.assertEqual(actual_key, expected_key) # 2) file read_data = '{ \"key\" : \"%s\" }' %",
"<reponame>homdx/EtherollApp<gh_stars>0 import unittest from unittest import mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase):",
"= '{ \"key\" : \"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as",
"from unittest import mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\"",
"mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies",
"= get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning was logged self.assertTrue( 'Cannot",
"# verifies the fallback warning was logged self.assertTrue( 'Cannot get Etherscan API key.'",
"as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken',",
"2) file 3) or fallbacks on default key \"\"\" expected_key = '0102030405060708091011121314151617' #",
"}' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key,",
"the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or",
"mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key",
"file read_data = '{ \"key\" : \"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data))",
"key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key",
"with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies",
"mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data",
"import mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the",
"self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks on default key with mock.patch('builtins.open') as",
"m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning",
"mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key = get_etherscan_api_key() self.assertEqual(expected_key, actual_key) # verifies the",
"def test_get_etherscan_api_key(self): \"\"\" Verifies the key can be retrieved from either: 1) environment",
"key \"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}):",
"1) environment 2) file 3) or fallbacks on default key \"\"\" expected_key =",
"from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key can",
"or fallbacks on default key \"\"\" expected_key = '0102030405060708091011121314151617' # 1) environment with",
"file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks",
"read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks on default",
"environment 2) file 3) or fallbacks on default key \"\"\" expected_key = '0102030405060708091011121314151617'",
"on default key with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect =",
"from either: 1) environment 2) file 3) or fallbacks on default key \"\"\"",
"unittest import mock from pyetheroll.etherscan_utils import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies",
"# 2) file read_data = '{ \"key\" : \"%s\" }' % (expected_key) with",
"expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data = '{ \"key\"",
"= get_etherscan_api_key() self.assertEqual(actual_key, expected_key) # 2) file read_data = '{ \"key\" : \"%s\"",
"import get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key can be retrieved",
"expected_key = '0102030405060708091011121314151617' # 1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key =",
"actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the fallback warning was logged self.assertTrue(",
"get_etherscan_api_key class TestEtherscanlUtils(unittest.TestCase): def test_get_etherscan_api_key(self): \"\"\" Verifies the key can be retrieved from",
"\\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) #",
"1) environment with mock.patch.dict( 'os.environ', {'ETHERSCAN_API_KEY': expected_key}): actual_key = get_etherscan_api_key() self.assertEqual(actual_key, expected_key) #",
"\"key\" : \"%s\" }' % (expected_key) with mock.patch('builtins.open', mock.mock_open(read_data=read_data)) \\ as m_open: actual_key",
"verifies the fallback warning was logged self.assertTrue( 'Cannot get Etherscan API key.' in",
"Verifies the key can be retrieved from either: 1) environment 2) file 3)",
"m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks on default key with",
"self.assertEqual(expected_key, actual_key) # verifies the file was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode':",
"as m_logger: m_open.side_effect = FileNotFoundError actual_key = get_etherscan_api_key() self.assertEqual('YourApiKeyToken', actual_key) # verifies the",
"was read self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks on",
"can be retrieved from either: 1) environment 2) file 3) or fallbacks on",
"self.assertTrue( m_open.call_args_list[0][0][0].endswith( '/pyetheroll/api_key.json')) self.assertEqual(m_open.call_args_list[0][1], {'mode': 'r'}) # 3) or fallbacks on default key",
"with mock.patch('builtins.open') as m_open, \\ mock.patch('pyetheroll.etherscan_utils.logger') as m_logger: m_open.side_effect = FileNotFoundError actual_key ="
] |
[
"with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista",
"for k in kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') #",
"np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es, f_linear(x_es), '-') plt.plot(x_es, f_linear(x_es), '-')",
"= 0 kursy_lista = [] for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]),",
"> 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"]",
"statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\",",
"\", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max:",
"= interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es,",
"counter += 1 if counter > 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for",
"for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"]",
"interp1d import numpy as np with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',')",
"print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista]))",
"xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es, f_linear(x_es), '-') plt.plot(x_es,",
"for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es = [k[\"kurs_max\"]",
"max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es =",
"y_es, kind='linear') # xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es,",
"kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if counter > 5000:",
"csv import statistics from matplotlib import pyplot as plt from scipy.interpolate import interp1d",
"counter > 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\",",
"[k[\"kurs_max\"] for k in kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear')",
"k in kursy_lista])) y_es = [k[\"kurs_max\"] for k in kursy_lista] x_es = range(0,len(y_es))",
"csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista = [] for row in readCSV:",
"import csv import statistics from matplotlib import pyplot as plt from scipy.interpolate import",
"k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for",
"as plt from scipy.interpolate import interp1d import numpy as np with open('pknorlen_akcje.csv') as",
"x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1, len(y_es),",
"statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \",",
"from matplotlib import pyplot as plt from scipy.interpolate import interp1d import numpy as",
"as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista = []",
"readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if counter >",
"f_linear = interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es,",
"kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in",
"# xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es, f_linear(x_es), '-')",
"5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for",
"print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista]))",
"for k in kursy_lista])) y_es = [k[\"kurs_max\"] for k in kursy_lista] x_es =",
"kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es = [k[\"kurs_max\"] for k in",
"in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k",
"counter = 0 kursy_lista = [] for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\":",
"import pyplot as plt from scipy.interpolate import interp1d import numpy as np with",
"kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in",
"from scipy.interpolate import interp1d import numpy as np with open('pknorlen_akcje.csv') as csvfile: readCSV",
"1 if counter > 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in",
"if counter > 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista]))",
"= [k[\"kurs_max\"] for k in kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es,",
"import numpy as np with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV)",
"min([k[\"kurs_max\"] for k in kursy_lista])) y_es = [k[\"kurs_max\"] for k in kursy_lista] x_es",
"as np with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter =",
"[] for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter +=",
"\", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es",
"statistics from matplotlib import pyplot as plt from scipy.interpolate import interp1d import numpy",
"print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista]))",
"next(readCSV) counter = 0 kursy_lista = [] for row in readCSV: kursy_lista.append({\"data\": row[0],",
"print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es = [k[\"kurs_max\"] for k in kursy_lista]",
"interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o',",
"\"kurs_min\": float(row[6])}) counter += 1 if counter > 5000: break print(counter) print(\"Srednia: \",",
"import statistics from matplotlib import pyplot as plt from scipy.interpolate import interp1d import",
"= csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista = [] for row in",
"csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista = [] for",
"0 kursy_lista = [] for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\":",
"len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es, f_linear(x_es), '-') plt.plot(x_es, f_linear(x_es), '-') plt.show()",
"np with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0",
"numpy as np with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter",
"in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es = [k[\"kurs_max\"] for k",
"= np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es, f_linear(x_es), '-') plt.plot(x_es, f_linear(x_es),",
"in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k",
"row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if counter > 5000: break",
"k in kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') # xnew",
"in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if counter",
"k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for k in kursy_lista])) y_es = [k[\"kurs_max\"] for",
"k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"] for k in kursy_lista])) print(\"Min:\", min([k[\"kurs_max\"] for",
"\"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if counter > 5000: break print(counter)",
"scipy.interpolate import interp1d import numpy as np with open('pknorlen_akcje.csv') as csvfile: readCSV =",
"float(row[6])}) counter += 1 if counter > 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"]",
"pyplot as plt from scipy.interpolate import interp1d import numpy as np with open('pknorlen_akcje.csv')",
"print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in",
"+= 1 if counter > 5000: break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k",
"delimiter=',') next(readCSV) counter = 0 kursy_lista = [] for row in readCSV: kursy_lista.append({\"data\":",
"kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1,",
"range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1, len(y_es), 0.1) #",
"import interp1d import numpy as np with open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile,",
"break print(counter) print(\"Srednia: \", statistics.mean([k[\"kurs_max\"] for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k",
"for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1",
"kind='linear') # xnew = np.arange(1, len(y_es), 0.1) # plt.plot(x_es, y_es, 'o', x_es, f_linear(x_es),",
"in kursy_lista])) y_es = [k[\"kurs_max\"] for k in kursy_lista] x_es = range(0,len(y_es)) f_linear",
"kursy_lista = [] for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])})",
"= range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') # xnew = np.arange(1, len(y_es), 0.1)",
"float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if counter > 5000: break print(counter) print(\"Srednia:",
"= [] for row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter",
"for k in kursy_lista])) print(\"Odch.Std:\", statistics.stdev([k[\"kurs_max\"] for k in kursy_lista])) print(\"Max: \", max([k[\"kurs_max\"]",
"in kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es, y_es, kind='linear') # xnew =",
"kursy_lista])) y_es = [k[\"kurs_max\"] for k in kursy_lista] x_es = range(0,len(y_es)) f_linear =",
"matplotlib import pyplot as plt from scipy.interpolate import interp1d import numpy as np",
"open('pknorlen_akcje.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista =",
"row in readCSV: kursy_lista.append({\"data\": row[0], \"kurs_max\": float(row[5]), \"kurs_min\": float(row[6])}) counter += 1 if",
"readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) counter = 0 kursy_lista = [] for row",
"plt from scipy.interpolate import interp1d import numpy as np with open('pknorlen_akcje.csv') as csvfile:",
"y_es = [k[\"kurs_max\"] for k in kursy_lista] x_es = range(0,len(y_es)) f_linear = interp1d(x_es,"
] |
[
"reader def read_data(): data = [] with open (\"data.csv\", \"r\") as f: csv_reader",
"read_data(): data = [] with open (\"data.csv\", \"r\") as f: csv_reader = reader(f)",
"next(csv_reader) if header != None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open",
"data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as f: for eachitem in data: f.write(eachitem",
"reader(f) header = next(csv_reader) if header != None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\"))",
"os import csv from csv import reader def read_data(): data = [] with",
"data = [] with open (\"data.csv\", \"r\") as f: csv_reader = reader(f) header",
"with open (\"data.csv\", \"r\") as f: csv_reader = reader(f) header = next(csv_reader) if",
"= reader(f) header = next(csv_reader) if header != None: for rows in csv_reader:",
"csv from csv import reader def read_data(): data = [] with open (\"data.csv\",",
"from csv import reader def read_data(): data = [] with open (\"data.csv\", \"r\")",
"if header != None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\",",
"csv_reader = reader(f) header = next(csv_reader) if header != None: for rows in",
"for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as f: for",
"open (\"data.csv\", \"r\") as f: csv_reader = reader(f) header = next(csv_reader) if header",
"f: csv_reader = reader(f) header = next(csv_reader) if header != None: for rows",
"rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as f: for eachitem",
"import csv from csv import reader def read_data(): data = [] with open",
"header = next(csv_reader) if header != None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data)",
"csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as f: for eachitem in data:",
"import os import csv from csv import reader def read_data(): data = []",
"open (\"data1.csv\", \"w\") as f: for eachitem in data: f.write(eachitem + \"\\n\") read_data()",
"[] with open (\"data.csv\", \"r\") as f: csv_reader = reader(f) header = next(csv_reader)",
"= next(csv_reader) if header != None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with",
"def read_data(): data = [] with open (\"data.csv\", \"r\") as f: csv_reader =",
"csv import reader def read_data(): data = [] with open (\"data.csv\", \"r\") as",
"None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as f:",
"with open (\"data1.csv\", \"w\") as f: for eachitem in data: f.write(eachitem + \"\\n\")",
"= [] with open (\"data.csv\", \"r\") as f: csv_reader = reader(f) header =",
"import reader def read_data(): data = [] with open (\"data.csv\", \"r\") as f:",
"as f: csv_reader = reader(f) header = next(csv_reader) if header != None: for",
"!= None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as",
"in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\") as f: for eachitem in",
"(\"data.csv\", \"r\") as f: csv_reader = reader(f) header = next(csv_reader) if header !=",
"header != None: for rows in csv_reader: data.append(rows[0].replace(\";\",\",\")) print(data) with open (\"data1.csv\", \"w\")",
"print(data) with open (\"data1.csv\", \"w\") as f: for eachitem in data: f.write(eachitem +",
"\"r\") as f: csv_reader = reader(f) header = next(csv_reader) if header != None:"
] |
[
"= link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont = 0",
"= ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont += 1",
"class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self):",
"get_product_price(self): cont = 0 for price in self.products: try: product_price = price.find('span', class_='price__fraction').string",
"image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont += 1 else:",
"bs4 import BeautifulSoup as bs import re import mysql.connector class Products_Infos(): def __init__(self,",
"UM ERRO AO LER O PREÇO DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price)",
"link in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def",
"= 0 for name in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont +=",
"price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER O PREÇO",
"product_price = price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string",
"= products self.productInfos = [] def insertSpaces(self): for i in self.products: self.productInfos.append([]) def",
"cont += 1 def get_product_name(self): cont = 0 for name in self.products: product_name",
"in self.products: try: product_price = price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text'))",
"class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM",
"price in self.products: try: product_price = price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div',",
"cont += 1 def get_shipping_info(self): cont = 0 for ship in self.products: try:",
"cont = 0 for link in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link)",
"self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont",
"0 for price in self.products: try: product_price = price.find('span', class_='price__fraction').string except: try: product_price_label",
"from bs4 import BeautifulSoup as bs import re import mysql.connector class Products_Infos(): def",
"in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont",
"= product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER O PREÇO DO PRODUTO') cont",
"self.products = products self.productInfos = [] def insertSpaces(self): for i in self.products: self.productInfos.append([])",
"1 def get_product_price(self): cont = 0 for price in self.products: try: product_price =",
"print('HOUVE UM ERRO AO LER O PREÇO DO PRODUTO') cont += 1 else:",
"1 else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont = 0 for image",
"product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER O PREÇO DO PRODUTO')",
"product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER O PREÇO DO PRODUTO') cont +=",
"ERRO AO LER O PREÇO DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont",
"= price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except:",
"1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont = 0 for",
"class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER O PREÇO DO",
"self.products: try: product_price = price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price",
"self.productInfos = [] def insertSpaces(self): for i in self.products: self.productInfos.append([]) def get_product_link(self): cont",
"cont += 1 else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont = 0",
"1 def get_product_name(self): cont = 0 for name in self.products: product_name = name.find('span',",
"item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont = 0 for name in",
"class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont = 0 for name",
"product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont = 0",
"self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont = 0 for ship in self.products:",
"name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont = 0 for price",
"PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont",
"= name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont = 0 for",
"mysql.connector class Products_Infos(): def __init__(self, products): self.products = products self.productInfos = [] def",
"self.products: self.productInfos.append([]) def get_product_link(self): cont = 0 for link in self.products: product_link =",
"LER O PREÇO DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont += 1",
"try: product_price = price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price =",
"product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER",
"get_shipping_info(self): cont = 0 for ship in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string",
"else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self):",
"print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont = 0 for ship",
"def insertSpaces(self): for i in self.products: self.productInfos.append([]) def get_product_link(self): cont = 0 for",
"ship in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1",
"cont = 0 for price in self.products: try: product_price = price.find('span', class_='price__fraction').string except:",
"self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont = 0 for image in self.products:",
"ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont += 1 def",
"get_product_name(self): cont = 0 for name in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name)",
"insertSpaces(self): for i in self.products: self.productInfos.append([]) def get_product_link(self): cont = 0 for link",
"= [] def insertSpaces(self): for i in self.products: self.productInfos.append([]) def get_product_link(self): cont =",
"self.productInfos.append([]) def get_product_link(self): cont = 0 for link in self.products: product_link = link.find('a',",
"for name in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def",
"self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont = 0 for price in self.products:",
"name in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self):",
"+= 1 def get_shipping_info(self): cont = 0 for ship in self.products: try: product_shipping_info",
"= 0 for price in self.products: try: product_price = price.find('span', class_='price__fraction').string except: try:",
"def get_product_link(self): cont = 0 for link in self.products: product_link = link.find('a', class_='item-link",
"= image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont += 1",
"except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont",
"in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else:",
"0 for link in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont +=",
"for link in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1",
"get_product_link(self): cont = 0 for link in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href')",
"def get_product_image(self): cont = 0 for image in self.products: try: product_image = image.find('img',",
"else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont = 0 for image in",
"= 0 for link in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont",
"Products_Infos(): def __init__(self, products): self.products = products self.productInfos = [] def insertSpaces(self): for",
"__init__(self, products): self.products = products self.productInfos = [] def insertSpaces(self): for i in",
"0 for name in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1",
"+= 1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1",
"for i in self.products: self.productInfos.append([]) def get_product_link(self): cont = 0 for link in",
"import BeautifulSoup as bs import re import mysql.connector class Products_Infos(): def __init__(self, products):",
"cont += 1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont +=",
"self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont = 0 for name in self.products:",
"def __init__(self, products): self.products = products self.productInfos = [] def insertSpaces(self): for i",
"try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont",
"cont = 0 for ship in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except:",
"cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont =",
"else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont = 0 for ship in",
"product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont =",
"1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def",
"in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM')",
"cont = 0 for image in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except:",
"PREÇO DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else:",
"def get_product_price(self): cont = 0 for price in self.products: try: product_price = price.find('span',",
"cont += 1 def get_product_image(self): cont = 0 for image in self.products: try:",
"in self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self):",
"in self.products: self.productInfos.append([]) def get_product_link(self): cont = 0 for link in self.products: product_link",
"link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont = 0 for",
"self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\")",
"+= 1 def get_product_price(self): cont = 0 for price in self.products: try: product_price",
"i in self.products: self.productInfos.append([]) def get_product_link(self): cont = 0 for link in self.products:",
"except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO",
"= 0 for image in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO",
"= 0 for ship in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0)",
"try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont",
"import mysql.connector class Products_Infos(): def __init__(self, products): self.products = products self.productInfos = []",
"AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont += 1 else: self.productInfos[cont].append(product_image) cont += 1",
"1 def get_product_image(self): cont = 0 for image in self.products: try: product_image =",
"class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont = 0 for price in",
"self.products: product_link = link.find('a', class_='item-link item__js-link').get('href') self.productInfos[cont].append(product_link) cont += 1 def get_product_name(self): cont",
"1 def get_shipping_info(self): cont = 0 for ship in self.products: try: product_shipping_info =",
"price.find('span', class_='price__fraction').string except: try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE",
"except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont += 1 else: self.productInfos[cont].append(product_image) cont",
"+= 1 def get_product_name(self): cont = 0 for name in self.products: product_name =",
"image in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A",
"import re import mysql.connector class Products_Infos(): def __init__(self, products): self.products = products self.productInfos",
"def get_shipping_info(self): cont = 0 for ship in self.products: try: product_shipping_info = ship.find('span',",
"DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price) else: self.productInfos[cont].append(product_price)",
"product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont +=",
"bs import re import mysql.connector class Products_Infos(): def __init__(self, products): self.products = products",
"as bs import re import mysql.connector class Products_Infos(): def __init__(self, products): self.products =",
"BeautifulSoup as bs import re import mysql.connector class Products_Infos(): def __init__(self, products): self.products",
"AO LER O PREÇO DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont +=",
"get_product_image(self): cont = 0 for image in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src')",
"product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont +=",
"for image in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER",
"def get_product_name(self): cont = 0 for name in self.products: product_name = name.find('span', class_='main-title').string",
"cont = 0 for name in self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont",
"products): self.products = products self.productInfos = [] def insertSpaces(self): for i in self.products:",
"re import mysql.connector class Products_Infos(): def __init__(self, products): self.products = products self.productInfos =",
"for price in self.products: try: product_price = price.find('span', class_='price__fraction').string except: try: product_price_label =",
"self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1)",
"print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont += 1 else: self.productInfos[cont].append(product_image) cont +=",
"src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO LER A IMAGEM') self.productInfos[cont].append(\"\") cont += 1 else: self.productInfos[cont].append(product_image)",
"+= 1 def get_product_image(self): cont = 0 for image in self.products: try: product_image",
"= price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO AO LER O",
"except: print('HOUVE UM ERRO AO LER O PREÇO DO PRODUTO') cont += 1",
"self.products: product_name = name.find('span', class_='main-title').string self.productInfos[cont].append(product_name) cont += 1 def get_product_price(self): cont =",
"for ship in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont +=",
"self.productInfos[cont].append(0) cont += 1 else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont =",
"cont += 1 def get_product_price(self): cont = 0 for price in self.products: try:",
"class Products_Infos(): def __init__(self, products): self.products = products self.productInfos = [] def insertSpaces(self):",
"0 for ship in self.products: try: product_shipping_info = ship.find('span', class_='text-shipping').string except: self.productInfos[cont].append(0) cont",
"O PREÇO DO PRODUTO') cont += 1 else: self.productInfos[cont].append(product_price) cont += 1 print(product_price)",
"try: product_price_label = price.find('div', class_=re.compile('pdp_options__text')) product_price = product_price_label.find('span').string except: print('HOUVE UM ERRO AO",
"0 for image in self.products: try: product_image = image.find('img', src=re.compile('https://http2.mlstatic.com')).get('src') except: print('ERRO AO",
"products self.productInfos = [] def insertSpaces(self): for i in self.products: self.productInfos.append([]) def get_product_link(self):",
"+= 1 else: self.productInfos[cont].append(1) cont += 1 def get_product_image(self): cont = 0 for",
"+= 1 print(product_price) else: self.productInfos[cont].append(product_price) cont += 1 def get_shipping_info(self): cont = 0",
"[] def insertSpaces(self): for i in self.products: self.productInfos.append([]) def get_product_link(self): cont = 0"
] |
[
"credentials file: # The DirectAdmin Server url # include the scheme and the",
"warning will be emitted each time Certbot uses the credentials file, including for",
"configuration file\", followed by the path to the credentials file. This warning will",
"-------- .. code-block:: bash :caption: To acquire a certificate for ``example.com`` certbot certonly",
"# The DirectAdmin Server url # include the scheme and the port number",
"path to the credentials file. This warning will be emitted each time Certbot",
"========================================================================================================= Credentials ----------- Use of this plugin requires an account on a DirectAdmin",
"on a DirectAdmin Server. Supported are both Username/Password authentication or Login Key. To",
"to create a key with the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` *",
"be provided interactively or using the ``--directadmin-credentials`` command-line argument. Certbot records the path",
"for ``example.com``, waiting 120 seconds for DNS propagation certbot certonly \\\\ --authenticator directadmin",
"store the file's contents. .. caution:: You should protect these API credentials as",
"The warning reads \"Unsafe permissions on credentials configuration file\", followed by the path",
"a single certificate for both ``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin",
"``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_ ..",
"records using the DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file.",
"``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of seconds to wait for",
"ini :name: directadmin.ini :caption: Example credentials file: # The DirectAdmin Server url #",
"the ACME server to verify the DNS record. (Default: 60) ========================================================================================================= Credentials -----------",
"seconds to wait for DNS to propagate before asking the ACME server to",
"for DNS to propagate before asking the ACME server to verify the DNS",
"will need to create a key with the following permissions: * ``CMD_API_LOGIN_TEST`` *",
"a password. Users who can read this file can use these credentials to",
"password directadmin_password = <PASSWORD> The path to this file can be provided interactively",
"be emitted each time Certbot uses the credentials file, including for renewal, and",
"interactively or using the ``--directadmin-credentials`` command-line argument. Certbot records the path to this",
"username directadmin_username = username # The DirectAdmin password directadmin_password = <PASSWORD> The path",
"``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com ..",
"issue some types of API calls on your behalf, limited by the permissions",
"API credentials as you would a password. Users who can read this file",
"Certbot to run using these credentials can complete a ``dns-01`` challenge to acquire",
"Examples -------- .. code-block:: bash :caption: To acquire a certificate for ``example.com`` certbot",
"to the credentials file. This warning will be emitted each time Certbot uses",
"number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username = username",
"or Login Key. To use Login Key authentication (Recommended) you will need to",
"# The DirectAdmin password directadmin_password = <PASSWORD> The path to this file can",
"argument. Certbot records the path to this file for use during renewal, but",
"acquire a single certificate for both ``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator",
"followed by the path to the credentials file. This warning will be emitted",
"to wait for DNS to propagate before asking the ACME server to verify",
"directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com .. code-block:: bash",
"bash :caption: To acquire a single certificate for both ``example.com`` and ``www.example.com`` certbot",
"120 seconds for DNS propagation certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini",
"Login Key. To use Login Key authentication (Recommended) you will need to create",
"path to this file for use during renewal, but does not store the",
":name: directadmin.ini :caption: Example credentials file: # The DirectAdmin Server url # include",
"domains these credentials are authorized to manage. Certbot will emit a warning if",
"silenced except by addressing the issue (e.g., by using a command like ``chmod",
"username # The DirectAdmin password directadmin_password = <PASSWORD> The path to this file",
"contents. .. caution:: You should protect these API credentials as you would a",
"plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and",
"and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com",
"\\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com ..",
"ACME server to verify the DNS record. (Default: 60) ========================================================================================================= Credentials ----------- Use",
"The `~certbot-dns-directadmin:directadmin` plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by",
"file for use during renewal, but does not store the file's contents. ..",
"``example.com``, waiting 120 seconds for DNS propagation certbot certonly \\\\ --authenticator directadmin \\\\",
"(Required) ``--directadmin-propagation-seconds`` The number of seconds to wait for DNS to propagate before",
"certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block::",
"file can be accessed by other users on your system. The warning reads",
"it detects that the credentials file can be accessed by other users on",
"Key. To use Login Key authentication (Recommended) you will need to create a",
"calls on your behalf, limited by the permissions assigned to the account. Users",
"to the file). Examples -------- .. code-block:: bash :caption: To acquire a certificate",
"run using these credentials can complete a ``dns-01`` challenge to acquire new certificates",
"acquire a certificate for ``example.com``, waiting 120 seconds for DNS propagation certbot certonly",
"be silenced except by addressing the issue (e.g., by using a command like",
".. code-block:: bash :caption: To acquire a single certificate for both ``example.com`` and",
"DNS propagation certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ --directadmin-propagation-seconds 120",
"users on your system. The warning reads \"Unsafe permissions on credentials configuration file\",",
"account on a DirectAdmin Server. Supported are both Username/Password authentication or Login Key.",
"can be accessed by other users on your system. The warning reads \"Unsafe",
"\\\\ -d example.com \\\\ -d www.example.com .. code-block:: bash :caption: To acquire a",
"your system. The warning reads \"Unsafe permissions on credentials configuration file\", followed by",
"``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a login key",
"certificate for ``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d",
"creating, and subsequently removing, TXT records using the DirectAdmin API. Named Arguments ---------------",
"number of seconds to wait for DNS to propagate before asking the ACME",
"the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing,",
"cause Certbot to run using these credentials can complete a ``dns-01`` challenge to",
"would a password. Users who can read this file can use these credentials",
"types of API calls on your behalf, limited by the permissions assigned to",
"can use these credentials to issue some types of API calls on your",
"the issue (e.g., by using a command like ``chmod 600`` to restrict access",
"to the account. Users who can cause Certbot to run using these credentials",
"Use of this plugin requires an account on a DirectAdmin Server. Supported are",
"asking the ACME server to verify the DNS record. (Default: 60) ========================================================================================================= Credentials",
"The DirectAdmin password directadmin_password = <PASSWORD> The path to this file can be",
"accessed by other users on your system. The warning reads \"Unsafe permissions on",
"the ``--directadmin-credentials`` command-line argument. Certbot records the path to this file for use",
"path to this file can be provided interactively or using the ``--directadmin-credentials`` command-line",
"will be emitted each time Certbot uses the credentials file, including for renewal,",
"these credentials to issue some types of API calls on your behalf, limited",
"API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number",
"this file for use during renewal, but does not store the file's contents.",
"`here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption: Example credentials file: # The",
".. code-block:: bash :caption: To acquire a certificate for ``example.com`` certbot certonly \\\\",
"DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of seconds to wait for DNS",
"-d www.example.com .. code-block:: bash :caption: To acquire a certificate for ``example.com``, waiting",
":caption: To acquire a certificate for ``example.com``, waiting 120 seconds for DNS propagation",
"time Certbot uses the credentials file, including for renewal, and cannot be silenced",
"manage. Certbot will emit a warning if it detects that the credentials file",
"removing, TXT records using the DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin",
"* ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_",
"https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username = username # The DirectAdmin password directadmin_password",
"challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the DirectAdmin API.",
"to acquire new certificates or revoke existing certificates for domains these credentials are",
"url # include the scheme and the port number (Normally 2222) directadmin_url =",
"for both ``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini",
"file. (Required) ``--directadmin-propagation-seconds`` The number of seconds to wait for DNS to propagate",
"code-block:: bash :caption: To acquire a certificate for ``example.com``, waiting 120 seconds for",
"single certificate for both ``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\",
"use Login Key authentication (Recommended) you will need to create a key with",
"by creating, and subsequently removing, TXT records using the DirectAdmin API. Named Arguments",
"(Default: 60) ========================================================================================================= Credentials ----------- Use of this plugin requires an account on",
"propagate before asking the ACME server to verify the DNS record. (Default: 60)",
"or using the ``--directadmin-credentials`` command-line argument. Certbot records the path to this file",
"\\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash :caption:",
"are authorized to manage. Certbot will emit a warning if it detects that",
"plugin requires an account on a DirectAdmin Server. Supported are both Username/Password authentication",
"To use Login Key authentication (Recommended) you will need to create a key",
"like ``chmod 600`` to restrict access to the file). Examples -------- .. code-block::",
"a login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption: Example",
"including for renewal, and cannot be silenced except by addressing the issue (e.g.,",
"both Username/Password authentication or Login Key. To use Login Key authentication (Recommended) you",
"* ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a login key -",
"``--directadmin-credentials`` command-line argument. Certbot records the path to this file for use during",
"(`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the DirectAdmin API. Named",
"these API credentials as you would a password. Users who can read this",
"permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a",
"file can use these credentials to issue some types of API calls on",
"scheme and the port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin",
"certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d",
"the DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds``",
"verify the DNS record. (Default: 60) ========================================================================================================= Credentials ----------- Use of this plugin",
"server to verify the DNS record. (Default: 60) ========================================================================================================= Credentials ----------- Use of",
"creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption:",
"addressing the issue (e.g., by using a command like ``chmod 600`` to restrict",
"to run using these credentials can complete a ``dns-01`` challenge to acquire new",
"these credentials are authorized to manage. Certbot will emit a warning if it",
"The DirectAdmin Server url # include the scheme and the port number (Normally",
"uses the credentials file, including for renewal, and cannot be silenced except by",
"certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ --directadmin-propagation-seconds 120 \\\\ -d example.com",
"subsequently removing, TXT records using the DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials``",
"new certificates or revoke existing certificates for domains these credentials are authorized to",
"emit a warning if it detects that the credentials file can be accessed",
"command-line argument. Certbot records the path to this file for use during renewal,",
"``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\",
"bash :caption: To acquire a certificate for ``example.com``, waiting 120 seconds for DNS",
".. caution:: You should protect these API credentials as you would a password.",
"you will need to create a key with the following permissions: * ``CMD_API_LOGIN_TEST``",
"during renewal, but does not store the file's contents. .. caution:: You should",
"and cannot be silenced except by addressing the issue (e.g., by using a",
"on credentials configuration file\", followed by the path to the credentials file. This",
"certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash",
"each time Certbot uses the credentials file, including for renewal, and cannot be",
"access to the file). Examples -------- .. code-block:: bash :caption: To acquire a",
"a ``dns-01`` challenge to acquire new certificates or revoke existing certificates for domains",
"\\\\ -d example.com .. code-block:: bash :caption: To acquire a single certificate for",
"certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ --directadmin-propagation-seconds 120 \\\\ -d",
"requires an account on a DirectAdmin Server. Supported are both Username/Password authentication or",
"\\\\ -d www.example.com .. code-block:: bash :caption: To acquire a certificate for ``example.com``,",
"the file's contents. .. caution:: You should protect these API credentials as you",
"directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash :caption: To acquire",
"credentials as you would a password. Users who can read this file can",
"key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption: Example credentials file:",
"--------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of seconds to",
"directadmin_username = username # The DirectAdmin password directadmin_password = <PASSWORD> The path to",
"on your behalf, limited by the permissions assigned to the account. Users who",
"Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of seconds",
"of API calls on your behalf, limited by the permissions assigned to the",
"the credentials file, including for renewal, and cannot be silenced except by addressing",
"to issue some types of API calls on your behalf, limited by the",
"========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of seconds to wait",
"be accessed by other users on your system. The warning reads \"Unsafe permissions",
"include the scheme and the port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 #",
"to this file for use during renewal, but does not store the file's",
"directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username = username # The DirectAdmin",
"before asking the ACME server to verify the DNS record. (Default: 60) =========================================================================================================",
"can read this file can use these credentials to issue some types of",
"complete a ``dns-01`` challenge to acquire new certificates or revoke existing certificates for",
"your behalf, limited by the permissions assigned to the account. Users who can",
"-d example.com \\\\ -d www.example.com .. code-block:: bash :caption: To acquire a certificate",
"``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d",
"acquire new certificates or revoke existing certificates for domains these credentials are authorized",
"To acquire a certificate for ``example.com``, waiting 120 seconds for DNS propagation certbot",
"60) ========================================================================================================= Credentials ----------- Use of this plugin requires an account on a",
"# include the scheme and the port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222",
"a warning if it detects that the credentials file can be accessed by",
"DirectAdmin Server. Supported are both Username/Password authentication or Login Key. To use Login",
"to manage. Certbot will emit a warning if it detects that the credentials",
"DirectAdmin Server url # include the scheme and the port number (Normally 2222)",
"example.com .. code-block:: bash :caption: To acquire a single certificate for both ``example.com``",
"To acquire a single certificate for both ``example.com`` and ``www.example.com`` certbot certonly \\\\",
"``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a login key - `here",
"Certbot records the path to this file for use during renewal, but does",
"of seconds to wait for DNS to propagate before asking the ACME server",
"\\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com .. code-block:: bash :caption:",
"= <PASSWORD> The path to this file can be provided interactively or using",
"process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT",
"renewal, but does not store the file's contents. .. caution:: You should protect",
"the permissions assigned to the account. Users who can cause Certbot to run",
"revoke existing certificates for domains these credentials are authorized to manage. Certbot will",
"certificate for both ``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials",
"--authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash :caption: To",
"the path to this file for use during renewal, but does not store",
"certificate for ``example.com``, waiting 120 seconds for DNS propagation certbot certonly \\\\ --authenticator",
"Username/Password authentication or Login Key. To use Login Key authentication (Recommended) you will",
":caption: To acquire a single certificate for both ``example.com`` and ``www.example.com`` certbot certonly",
"credentials are authorized to manage. Certbot will emit a warning if it detects",
"a certificate for ``example.com``, waiting 120 seconds for DNS propagation certbot certonly \\\\",
"code-block:: bash :caption: To acquire a single certificate for both ``example.com`` and ``www.example.com``",
"DirectAdmin username directadmin_username = username # The DirectAdmin password directadmin_password = <PASSWORD> The",
"wait for DNS to propagate before asking the ACME server to verify the",
"will emit a warning if it detects that the credentials file can be",
"and subsequently removing, TXT records using the DirectAdmin API. Named Arguments --------------- =========================================================================================================",
"to propagate before asking the ACME server to verify the DNS record. (Default:",
"cannot be silenced except by addressing the issue (e.g., by using a command",
"or revoke existing certificates for domains these credentials are authorized to manage. Certbot",
"the scheme and the port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The",
"to this file can be provided interactively or using the ``--directadmin-credentials`` command-line argument.",
"a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the",
"a DirectAdmin Server. Supported are both Username/Password authentication or Login Key. To use",
"the file). Examples -------- .. code-block:: bash :caption: To acquire a certificate for",
"~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash :caption: To acquire a single certificate",
"certificates or revoke existing certificates for domains these credentials are authorized to manage.",
"Certbot uses the credentials file, including for renewal, and cannot be silenced except",
"should protect these API credentials as you would a password. Users who can",
"who can cause Certbot to run using these credentials can complete a ``dns-01``",
"DirectAdmin provides instructions for creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block::",
"certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com",
"waiting 120 seconds for DNS propagation certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials",
"www.example.com .. code-block:: bash :caption: To acquire a certificate for ``example.com``, waiting 120",
"for renewal, and cannot be silenced except by addressing the issue (e.g., by",
"using the ``--directadmin-credentials`` command-line argument. Certbot records the path to this file for",
"The DirectAdmin username directadmin_username = username # The DirectAdmin password directadmin_password = <PASSWORD>",
"certificates for domains these credentials are authorized to manage. Certbot will emit a",
"file, including for renewal, and cannot be silenced except by addressing the issue",
"the credentials file. This warning will be emitted each time Certbot uses the",
"This warning will be emitted each time Certbot uses the credentials file, including",
"credentials file, including for renewal, and cannot be silenced except by addressing the",
":caption: Example credentials file: # The DirectAdmin Server url # include the scheme",
"directadmin_password = <PASSWORD> The path to this file can be provided interactively or",
"system. The warning reads \"Unsafe permissions on credentials configuration file\", followed by the",
"(Recommended) you will need to create a key with the following permissions: *",
"issue (e.g., by using a command like ``chmod 600`` to restrict access to",
"for creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini",
"renewal, and cannot be silenced except by addressing the issue (e.g., by using",
"code-block:: ini :name: directadmin.ini :caption: Example credentials file: # The DirectAdmin Server url",
"the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for",
"the account. Users who can cause Certbot to run using these credentials can",
"by other users on your system. The warning reads \"Unsafe permissions on credentials",
"key with the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides",
"existing certificates for domains these credentials are authorized to manage. Certbot will emit",
"Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of seconds to wait for DNS to",
"``--directadmin-propagation-seconds`` The number of seconds to wait for DNS to propagate before asking",
"except by addressing the issue (e.g., by using a command like ``chmod 600``",
"for DNS propagation certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ --directadmin-propagation-seconds",
"record. (Default: 60) ========================================================================================================= Credentials ----------- Use of this plugin requires an account",
"\\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ --directadmin-propagation-seconds 120 \\\\ -d example.com \"\"\"",
"DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The",
"Supported are both Username/Password authentication or Login Key. To use Login Key authentication",
"need to create a key with the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL``",
"can complete a ``dns-01`` challenge to acquire new certificates or revoke existing certificates",
"600`` to restrict access to the file). Examples -------- .. code-block:: bash :caption:",
"\\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash :caption: To acquire a",
"To acquire a certificate for ``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials",
"read this file can use these credentials to issue some types of API",
"restrict access to the file). Examples -------- .. code-block:: bash :caption: To acquire",
"Server. Supported are both Username/Password authentication or Login Key. To use Login Key",
"following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating",
"acquire a certificate for ``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini",
"file). Examples -------- .. code-block:: bash :caption: To acquire a certificate for ``example.com``",
"use during renewal, but does not store the file's contents. .. caution:: You",
"(e.g., by using a command like ``chmod 600`` to restrict access to the",
"credentials to issue some types of API calls on your behalf, limited by",
"other users on your system. The warning reads \"Unsafe permissions on credentials configuration",
"can be provided interactively or using the ``--directadmin-credentials`` command-line argument. Certbot records the",
"challenge to acquire new certificates or revoke existing certificates for domains these credentials",
"a certificate for ``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\",
"-d example.com .. code-block:: bash :caption: To acquire a single certificate for both",
"by the permissions assigned to the account. Users who can cause Certbot to",
"file's contents. .. caution:: You should protect these API credentials as you would",
"limited by the permissions assigned to the account. Users who can cause Certbot",
"login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption: Example credentials",
".. code-block:: ini :name: directadmin.ini :caption: Example credentials file: # The DirectAdmin Server",
"* ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions for creating a login",
"use these credentials to issue some types of API calls on your behalf,",
"port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username =",
"<reponame>cybercinch/certbot-dns-directadmin \"\"\" The `~certbot-dns-directadmin:directadmin` plugin automates the process of completing a ``dns-01`` challenge",
"authentication (Recommended) you will need to create a key with the following permissions:",
"`~certbot-dns-directadmin:directadmin` plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating,",
"a command like ``chmod 600`` to restrict access to the file). Examples --------",
"bash :caption: To acquire a certificate for ``example.com`` certbot certonly \\\\ --authenticator directadmin",
".. code-block:: bash :caption: To acquire a certificate for ``example.com``, waiting 120 seconds",
"authorized to manage. Certbot will emit a warning if it detects that the",
"Server url # include the scheme and the port number (Normally 2222) directadmin_url",
"Example credentials file: # The DirectAdmin Server url # include the scheme and",
"directadmin.ini :caption: Example credentials file: # The DirectAdmin Server url # include the",
"API calls on your behalf, limited by the permissions assigned to the account.",
"permissions on credentials configuration file\", followed by the path to the credentials file.",
"credentials file. This warning will be emitted each time Certbot uses the credentials",
"both ``example.com`` and ``www.example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\",
"file can be provided interactively or using the ``--directadmin-credentials`` command-line argument. Certbot records",
"2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username = username # The",
"``dns-01`` challenge to acquire new certificates or revoke existing certificates for domains these",
"emitted each time Certbot uses the credentials file, including for renewal, and cannot",
"completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using",
"- `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption: Example credentials file: #",
"Users who can read this file can use these credentials to issue some",
"reads \"Unsafe permissions on credentials configuration file\", followed by the path to the",
"by addressing the issue (e.g., by using a command like ``chmod 600`` to",
"to verify the DNS record. (Default: 60) ========================================================================================================= Credentials ----------- Use of this",
"example.com \\\\ -d www.example.com .. code-block:: bash :caption: To acquire a certificate for",
"You should protect these API credentials as you would a password. Users who",
"by the path to the credentials file. This warning will be emitted each",
"behalf, limited by the permissions assigned to the account. Users who can cause",
"Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required) ``--directadmin-propagation-seconds`` The number of",
"using these credentials can complete a ``dns-01`` challenge to acquire new certificates or",
"are both Username/Password authentication or Login Key. To use Login Key authentication (Recommended)",
"provides instructions for creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini",
"credentials file can be accessed by other users on your system. The warning",
"with the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin provides instructions",
"by using a command like ``chmod 600`` to restrict access to the file).",
"the DNS record. (Default: 60) ========================================================================================================= Credentials ----------- Use of this plugin requires",
"this file can use these credentials to issue some types of API calls",
"as you would a password. Users who can read this file can use",
"you would a password. Users who can read this file can use these",
"who can read this file can use these credentials to issue some types",
"password. Users who can read this file can use these credentials to issue",
"--authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com .. code-block::",
"this file can be provided interactively or using the ``--directadmin-credentials`` command-line argument. Certbot",
"warning reads \"Unsafe permissions on credentials configuration file\", followed by the path to",
"using the DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials file. (Required)",
"this plugin requires an account on a DirectAdmin Server. Supported are both Username/Password",
"permissions assigned to the account. Users who can cause Certbot to run using",
"file. This warning will be emitted each time Certbot uses the credentials file,",
"authentication or Login Key. To use Login Key authentication (Recommended) you will need",
"The path to this file can be provided interactively or using the ``--directadmin-credentials``",
"does not store the file's contents. .. caution:: You should protect these API",
"\"Unsafe permissions on credentials configuration file\", followed by the path to the credentials",
"``chmod 600`` to restrict access to the file). Examples -------- .. code-block:: bash",
"Key authentication (Recommended) you will need to create a key with the following",
"of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records",
"The number of seconds to wait for DNS to propagate before asking the",
"account. Users who can cause Certbot to run using these credentials can complete",
"credentials configuration file\", followed by the path to the credentials file. This warning",
"caution:: You should protect these API credentials as you would a password. Users",
"``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the DirectAdmin",
"a key with the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS`` DirectAdmin",
"file: # The DirectAdmin Server url # include the scheme and the port",
"can cause Certbot to run using these credentials can complete a ``dns-01`` challenge",
"for use during renewal, but does not store the file's contents. .. caution::",
"create a key with the following permissions: * ``CMD_API_LOGIN_TEST`` * ``CMD_API_DNS_CONTROL`` * ``CMD_API_SHOW_DOMAINS``",
"to restrict access to the file). Examples -------- .. code-block:: bash :caption: To",
"--directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com .. code-block:: bash :caption: To",
"these credentials can complete a ``dns-01`` challenge to acquire new certificates or revoke",
"~/.secrets/certbot/directadmin.ini \\\\ -d example.com \\\\ -d www.example.com .. code-block:: bash :caption: To acquire",
"seconds for DNS propagation certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\",
"<PASSWORD> The path to this file can be provided interactively or using the",
"Credentials ----------- Use of this plugin requires an account on a DirectAdmin Server.",
"the port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username",
"using a command like ``chmod 600`` to restrict access to the file). Examples",
"Login Key authentication (Recommended) you will need to create a key with the",
"provided interactively or using the ``--directadmin-credentials`` command-line argument. Certbot records the path to",
"warning if it detects that the credentials file can be accessed by other",
"command like ``chmod 600`` to restrict access to the file). Examples -------- ..",
"protect these API credentials as you would a password. Users who can read",
"file\", followed by the path to the credentials file. This warning will be",
"TXT records using the DirectAdmin API. Named Arguments --------------- ========================================================================================================= ``--directadmin-credentials`` DirectAdmin Credentials",
"Users who can cause Certbot to run using these credentials can complete a",
"for ``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com",
"\"\"\" The `~certbot-dns-directadmin:directadmin` plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`)",
"an account on a DirectAdmin Server. Supported are both Username/Password authentication or Login",
"propagation certbot certonly \\\\ --authenticator directadmin \\\\ --directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ --directadmin-propagation-seconds 120 \\\\",
"detects that the credentials file can be accessed by other users on your",
"Certbot will emit a warning if it detects that the credentials file can",
"--directadmin-credentials ~/.secrets/certbot/directadmin.ini \\\\ -d example.com .. code-block:: bash :caption: To acquire a single",
"not store the file's contents. .. caution:: You should protect these API credentials",
"if it detects that the credentials file can be accessed by other users",
"on your system. The warning reads \"Unsafe permissions on credentials configuration file\", followed",
"DNS record. (Default: 60) ========================================================================================================= Credentials ----------- Use of this plugin requires an",
"but does not store the file's contents. .. caution:: You should protect these",
"for domains these credentials are authorized to manage. Certbot will emit a warning",
"instructions for creating a login key - `here <https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name:",
"= https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username = username # The DirectAdmin password",
"(Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username directadmin_username = username #",
"credentials can complete a ``dns-01`` challenge to acquire new certificates or revoke existing",
"records the path to this file for use during renewal, but does not",
"and the port number (Normally 2222) directadmin_url = https://my.directadminserver.com:2222 # The DirectAdmin username",
"<https://help.directadmin.com/item.php?id=523>`_ .. code-block:: ini :name: directadmin.ini :caption: Example credentials file: # The DirectAdmin",
"automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently",
"the credentials file can be accessed by other users on your system. The",
"of this plugin requires an account on a DirectAdmin Server. Supported are both",
"the path to the credentials file. This warning will be emitted each time",
"DirectAdmin password directadmin_password = <PASSWORD> The path to this file can be provided",
":caption: To acquire a certificate for ``example.com`` certbot certonly \\\\ --authenticator directadmin \\\\",
"assigned to the account. Users who can cause Certbot to run using these",
"# The DirectAdmin username directadmin_username = username # The DirectAdmin password directadmin_password =",
"code-block:: bash :caption: To acquire a certificate for ``example.com`` certbot certonly \\\\ --authenticator",
"some types of API calls on your behalf, limited by the permissions assigned",
"DNS to propagate before asking the ACME server to verify the DNS record.",
"----------- Use of this plugin requires an account on a DirectAdmin Server. Supported",
"that the credentials file can be accessed by other users on your system.",
"= username # The DirectAdmin password directadmin_password = <PASSWORD> The path to this"
] |
[
"import BaseTestCase from .. import document from .. import run def deactivate(doc): document.activedocument",
"expected = 'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n',",
"self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel')",
"expected = '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12])",
"self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document)",
"= 'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12])",
"self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n",
"import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import",
"'\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import",
"self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel')",
"..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo from .basetestcase import",
"in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected =",
"selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel')",
"from ..undotree import undo from .basetestcase import BaseTestCase from .. import document from",
"def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self):",
".. import run def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self)",
"self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected, self.document.text[:len(expected)])",
"self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n",
"from .basetestcase import BaseTestCase from .. import document from .. import run def",
"run def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def",
"setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n':",
"in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n",
"= None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char",
"def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n",
"sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in",
"self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n",
"ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo from .basetestcase import BaseTestCase from",
"sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword)",
"indentation is covered. \"\"\" from ..commands import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter,",
"self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)':",
"def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate)",
"run() expected = '\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import",
"..commands import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree",
"\\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\nimport sys'",
"from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo from .basetestcase",
"for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run()",
"sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char)",
"BaseTestCase from .. import document from .. import run def deactivate(doc): document.activedocument =",
"\"\"\" from ..commands import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround",
"self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)])",
"\\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n \\n \\n \\n\\n'",
"import run def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document)",
"self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document)",
"self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected,",
"from .. import run def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self):",
"self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate)",
"\\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in",
"= '\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12])",
"'\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def",
"import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo from .basetestcase import BaseTestCase",
"from ..commands import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from",
"self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)])",
"\\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n \\n \\n",
"undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n",
"\\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n",
"ChangeAround from ..undotree import undo from .basetestcase import BaseTestCase from .. import document",
"\\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\nimport",
"= 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12])",
"\\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for",
"for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected =",
"self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b",
"\\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char",
"sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char)",
"undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n",
"ChangeInPlace, ChangeAround from ..undotree import undo from .basetestcase import BaseTestCase from .. import",
"char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas",
"import undo from .basetestcase import BaseTestCase from .. import document from .. import",
"..undotree import undo from .basetestcase import BaseTestCase from .. import document from ..",
"def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate)",
"\\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter)",
"\\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for",
"run() expected = 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) undo(self.document) self.assertEqual('import",
"expected = 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) undo(self.document) self.assertEqual('import sys\\n\\n',",
"is covered. \"\"\" from ..commands import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore,",
"\"\"\" This module provides testcases for insertoperations. Auto indentation is covered. \"\"\" from",
".. import document from .. import run def deactivate(doc): document.activedocument = None class",
"document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for",
"BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char)",
"document from .. import run def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def",
"self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected",
"\\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for",
"self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)])",
"selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo",
"expected = '\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n',",
"run() expected = 'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import",
"self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b",
"\\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char",
"self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel')",
"self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) undo(self.document)",
"\\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\n'",
"'\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n",
"'\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self):",
"self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document)",
"None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in",
"test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run()",
"from .. import document from .. import run def deactivate(doc): document.activedocument = None",
"self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround)",
"\\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n \\n",
"module provides testcases for insertoperations. Auto indentation is covered. \"\"\" from ..commands import",
"self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n hi\\n",
"test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run()",
"sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self):",
"self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected",
"self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n hi\\n )\\n'",
"import document from .. import run def deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase):",
"'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def",
"testcases for insertoperations. Auto indentation is covered. \"\"\" from ..commands import selectnextline, selectpreviousword",
"self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n':",
"char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected",
"self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected",
"self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n':",
"self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n",
"class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b",
"test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run()",
"self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import",
"run() expected = '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n',",
"\\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self): self.document.ui.feedinput(ChangeAfter)",
"def test_change_after(self): self.document.ui.feedinput(ChangeAfter) for char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate)",
"This module provides testcases for insertoperations. Auto indentation is covered. \"\"\" from ..commands",
"'\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n",
"test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel')",
"insertoperations. Auto indentation is covered. \"\"\" from ..commands import selectnextline, selectpreviousword from ..insertoperations",
"\\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char",
"char in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import",
"= '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def",
"provides testcases for insertoperations. Auto indentation is covered. \"\"\" from ..commands import selectnextline,",
"Auto indentation is covered. \"\"\" from ..commands import selectnextline, selectpreviousword from ..insertoperations import",
"in '\\nasdf\\b\\b \\n \\n \\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas",
"OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore) for char in '\\nasdf\\b\\b \\n",
"for insertoperations. Auto indentation is covered. \"\"\" from ..commands import selectnextline, selectpreviousword from",
"deactivate(doc): document.activedocument = None class OperatorTest(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) selectnextline(self.document) def test_change_before(self): self.document.ui.feedinput(ChangeBefore)",
".basetestcase import BaseTestCase from .. import document from .. import run def deactivate(doc):",
"self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected,",
"undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char)",
"self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\nimport sys' self.assertEqual(expected,",
"\\n \\n \\n \\n\\nimport sys' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_after(self):",
"\\n\\n\\b\\b\\n': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = '\\nas \\n \\n \\n \\n\\n' self.assertEqual(expected,",
"self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n (\\n hi\\n )\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document)",
"undo from .basetestcase import BaseTestCase from .. import document from .. import run",
"covered. \"\"\" from ..commands import selectnextline, selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace,",
"selectpreviousword from ..insertoperations import ChangeAfter, ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo from",
"ChangeBefore, ChangeInPlace, ChangeAround from ..undotree import undo from .basetestcase import BaseTestCase from ..",
"(hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n') self.document.ui.feedinput('Cancel') self.document.ui.feedinput(deactivate) run() expected = 'import sys\\n\\n",
"\\n \\n \\n \\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace)",
"def test_change_around(self): self.document.ui.feedinput(ChangeAfter) for char in '\\n\\n (hi)': self.document.ui.feedinput(char) self.document.ui.feedinput('Cancel') self.document.ui.feedinput(selectpreviousword) self.document.ui.feedinput(ChangeAround) self.document.ui.feedinput('\\n')",
"\\n\\n' self.assertEqual(expected, self.document.text[:len(expected)]) undo(self.document) self.assertEqual('import sys\\n\\n', self.document.text[:12]) def test_change_in_place(self): self.document.ui.feedinput(ChangeInPlace) for char in"
] |
[
"<reponame>appasahebs/bzTakeHome from django.urls import path from .views import BackfillView urlpatterns = [ path('',",
"import path from .views import BackfillView urlpatterns = [ path('', BackfillView.as_view(), name='list') ]",
"from django.urls import path from .views import BackfillView urlpatterns = [ path('', BackfillView.as_view(),",
"django.urls import path from .views import BackfillView urlpatterns = [ path('', BackfillView.as_view(), name='list')"
] |
[
"figure out inserting some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult",
"names rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] }",
"'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc better",
"FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two assignents to",
"= 'test' connection = ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname +",
"# Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can",
"} db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy the charactercreator_character table get_characters",
"at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's start the afternoon project rpg_character",
"working with MongoDB different from working with PostgreSQL? What was easier, and what",
"-In PostgreSQL there are schemas that are used to connect to individual data",
"a dictionary! # Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) #",
"\"\"\" \"\"\"first make shell and install pymongo and dnspython\"\"\" import pymongo password =",
"working with PostgreSQL? What was easier, and what was harder?\": -MongoDB and PostgrSQL",
"rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make",
"query on it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp':",
"make shell and install pymongo and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this!",
"is hpw the data/information is stored. -In PostgreSQL there are schemas that are",
"+ dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db = client.test dir(db.test) #",
"charactercreator_character table get_characters = 'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] #",
"We can do better # Mongo doesn't force us to have a schema,",
"was harder?\": -MongoDB and PostgrSQL biggest difference is hpw the data/information is stored.",
"We need key-value pairs, i.e. a dictionary! # Lazy way (probably not ideal)",
"rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc better -",
"on it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2],",
"1}) # 1 # Let's start the afternoon project rpg_character = (1, \"<NAME>\",",
"-MongoDB and PostgrSQL biggest difference is hpw the data/information is stored. -In PostgreSQL",
"dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this! Reset it if it leak User",
"list(db.test.find({'level': 3})) # Make our doc better - annotate type so we can",
"\"\"\"first make shell and install pymongo and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share",
"# <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's start the afternoon",
"\"\"\" \"How was working with MongoDB different from working with PostgreSQL? What was",
"rpg_character}) # We can do better # Mongo doesn't force us to have",
"useful/informative key names rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level':",
"Let's figure out inserting some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) #",
"what was harder?\": -MongoDB and PostgrSQL biggest difference is hpw the data/information is",
"0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's",
"so its harder. \"\"\" \"\"\"first make shell and install pymongo and dnspython\"\"\" import",
"harder. \"\"\" \"\"\"first make shell and install pymongo and dnspython\"\"\" import pymongo password",
"dir(db.test) # Let's figure out inserting some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x':",
"my opinion extra steps so its harder. \"\"\" \"\"\"first make shell and install",
"difference is hpw the data/information is stored. -In PostgreSQL there are schemas that",
"a schema, but # we *should* try to choose useful/informative key names rpg_doc",
"= ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client",
"dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname",
"but # we *should* try to choose useful/informative key names rpg_doc = {",
"are schemas that are used to connect to individual data tables. MongoDB formats",
"easier, and what was harder?\": -MongoDB and PostgrSQL biggest difference is hpw the",
"two have unique differences and but in my opinon MongoDB seems simpler/easier way",
"0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's start the afternoon project rpg_character =",
"ipecho.net/plain \"\"\" \"How was working with MongoDB different from working with PostgreSQL? What",
"Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do",
"leak User = 'John-Thomas' dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\" + password",
"it leak User = 'John-Thomas' dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\" +",
"the data formated in documents. The two have unique differences and but in",
"What was easier, and what was harder?\": -MongoDB and PostgrSQL biggest difference is",
"and stores the all the data formated in documents. The two have unique",
"extra steps so its harder. \"\"\" \"\"\"first make shell and install pymongo and",
"\"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db = client.test dir(db.test)",
"Let's start the afternoon project rpg_character = (1, \"<NAME>\", 10, 3, 0, 0,",
"db.test.find_one({'rpg_character': rpg_character}) # We can do better # Mongo doesn't force us to",
"formated in documents. The two have unique differences and but in my opinon",
"try to choose useful/informative key names rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1],",
"rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc",
"inserting some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208>",
"+ \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's figure",
"rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy the",
"and but in my opinon MongoDB seems simpler/easier way to store data and",
"unique differences and but in my opinon MongoDB seems simpler/easier way to store",
"{ 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc)",
"the charactercreator_character table get_characters = 'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10]",
"way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do better",
"in documents. The two have unique differences and but in my opinon MongoDB",
"# We can do better # Mongo doesn't force us to have a",
"goal - copy the charactercreator_character table get_characters = 'SELECT * FROM charactercreator_character;' characters",
"client.test dir(db.test) # Let's figure out inserting some data db.test.count_documents({'x': 1}) # 0",
"not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do better # Mongo",
"'test' connection = ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\"",
"have a schema, but # we *should* try to choose useful/informative key names",
"out inserting some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at",
"better # Mongo doesn't force us to have a schema, but # we",
"* FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two assignents",
"rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc better - annotate type",
"MongoDB seems simpler/easier way to store data and PostgreSQL has in my opinion",
"= 'John-Thomas' dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\"",
"1 # Let's start the afternoon project rpg_character = (1, \"<NAME>\", 10, 3,",
"sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two assignents to review and stufy guide",
"with MongoDB different from working with PostgreSQL? What was easier, and what was",
"from working with PostgreSQL? What was easier, and what was harder?\": -MongoDB and",
"all the data formated in documents. The two have unique differences and but",
"but in my opinon MongoDB seems simpler/easier way to store data and PostgreSQL",
"db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) #",
"if it leak User = 'John-Thomas' dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\"",
"!curl ipecho.net/plain \"\"\" \"How was working with MongoDB different from working with PostgreSQL?",
"and install pymongo and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this! Reset it",
"db.test.count_documents({'x': 1}) # 1 # Let's start the afternoon project rpg_character = (1,",
"do better # Mongo doesn't force us to have a schema, but #",
"rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy the charactercreator_character table",
"'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two",
"start the afternoon project rpg_character = (1, \"<NAME>\", 10, 3, 0, 0, 0)",
"connection = ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\")",
"'<PASSWORD>'commit/share this! Reset it if it leak User = 'John-Thomas' dbname = 'test'",
"password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db =",
"choose useful/informative key names rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2],",
"my opinon MongoDB seems simpler/easier way to store data and PostgreSQL has in",
"data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1})",
"copy the charactercreator_character table get_characters = 'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall()",
"opinion extra steps so its harder. \"\"\" \"\"\"first make shell and install pymongo",
"i.e. a dictionary! # Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character})",
"rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal -",
"= (1, \"<NAME>\", 10, 3, 0, 0, 0) # We need key-value pairs,",
"and PostgrSQL biggest difference is hpw the data/information is stored. -In PostgreSQL there",
"data formated in documents. The two have unique differences and but in my",
"us to have a schema, but # we *should* try to choose useful/informative",
"db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc better - annotate type so we",
"out the IP address of this Colab Instance # !curl ipecho.net/plain \"\"\" \"How",
"<pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's start the afternoon project",
"- copy the charactercreator_character table get_characters = 'SELECT * FROM charactercreator_character;' characters =",
"some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x':",
"this! Reset it if it leak User = 'John-Thomas' dbname = 'test' connection",
"the IP address of this Colab Instance # !curl ipecho.net/plain \"\"\" \"How was",
"10, 3, 0, 0, 0) # We need key-value pairs, i.e. a dictionary!",
"0, 0, 0) # We need key-value pairs, i.e. a dictionary! # Lazy",
"dictionary! # Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We",
"# Our goal - copy the charactercreator_character table get_characters = 'SELECT * FROM",
"= '<PASSWORD>'commit/share this! Reset it if it leak User = 'John-Thomas' dbname =",
"we *should* try to choose useful/informative key names rpg_doc = { 'sql_key': rpg_character[0],",
"address of this Colab Instance # !curl ipecho.net/plain \"\"\" \"How was working with",
"PostgreSQL? What was easier, and what was harder?\": -MongoDB and PostgrSQL biggest difference",
"connect to individual data tables. MongoDB formats and stores the all the data",
"The two have unique differences and but in my opinon MongoDB seems simpler/easier",
"MongoDB formats and stores the all the data formated in documents. The two",
"annotate type so we can query on it rpg_doc = { 'doc_type': 'rpg_character',",
"db = client.test dir(db.test) # Let's figure out inserting some data db.test.count_documents({'x': 1})",
"steps so its harder. \"\"\" \"\"\"first make shell and install pymongo and dnspython\"\"\"",
"data tables. MongoDB formats and stores the all the data formated in documents.",
"} db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc better - annotate type so",
"data and PostgreSQL has in my opinion extra steps so its harder. \"\"\"",
"# Mongo doesn't force us to have a schema, but # we *should*",
"can query on it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1],",
"db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's start",
"force us to have a schema, but # we *should* try to choose",
"store data and PostgreSQL has in my opinion extra steps so its harder.",
"import pymongo password = '<PASSWORD>'commit/share this! Reset it if it leak User =",
"to choose useful/informative key names rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp':",
"rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3]",
"schemas that are used to connect to individual data tables. MongoDB formats and",
"db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy the charactercreator_character table get_characters =",
"= client.test dir(db.test) # Let's figure out inserting some data db.test.count_documents({'x': 1}) #",
"its harder. \"\"\" \"\"\"first make shell and install pymongo and dnspython\"\"\" import pymongo",
"Mongo doesn't force us to have a schema, but # we *should* try",
"pymongo password = '<PASSWORD>'commit/share this! Reset it if it leak User = 'John-Thomas'",
"biggest difference is hpw the data/information is stored. -In PostgreSQL there are schemas",
"need key-value pairs, i.e. a dictionary! # Lazy way (probably not ideal) db.test.insert_one({'rpg_character':",
"*should* try to choose useful/informative key names rpg_doc = { 'sql_key': rpg_character[0], 'name':",
"# we *should* try to choose useful/informative key names rpg_doc = { 'sql_key':",
"Make our doc better - annotate type so we can query on it",
"rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our",
"was easier, and what was harder?\": -MongoDB and PostgrSQL biggest difference is hpw",
"hpw the data/information is stored. -In PostgreSQL there are schemas that are used",
"User = 'John-Thomas' dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\" + password +",
"differences and but in my opinon MongoDB seems simpler/easier way to store data",
"we can query on it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name':",
"this Colab Instance # !curl ipecho.net/plain \"\"\" \"How was working with MongoDB different",
"+ password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db",
"to store data and PostgreSQL has in my opinion extra steps so its",
"formats and stores the all the data formated in documents. The two have",
"'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy the charactercreator_character",
"\"=majority\") client = pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's figure out inserting",
"'John-Thomas' dbname = 'test' connection = ( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" +",
"rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc)",
"the afternoon project rpg_character = (1, \"<NAME>\", 10, 3, 0, 0, 0) #",
"better - annotate type so we can query on it rpg_doc = {",
"(1, \"<NAME>\", 10, 3, 0, 0, 0) # We need key-value pairs, i.e.",
"\"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's figure out",
"table get_characters = 'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked",
"opinon MongoDB seems simpler/easier way to store data and PostgreSQL has in my",
"1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 # Let's start the",
"0, 0) # We need key-value pairs, i.e. a dictionary! # Lazy way",
"ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do better # Mongo doesn't",
"{ 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3}))",
"our doc better - annotate type so we can query on it rpg_doc",
"Find out the IP address of this Colab Instance # !curl ipecho.net/plain \"\"\"",
"IP address of this Colab Instance # !curl ipecho.net/plain \"\"\" \"How was working",
"# Make our doc better - annotate type so we can query on",
"( \"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client =",
"# Let's figure out inserting some data db.test.count_documents({'x': 1}) # 0 db.test.insert_one({'x': 1})",
"MongoDB different from working with PostgreSQL? What was easier, and what was harder?\":",
"PostgreSQL there are schemas that are used to connect to individual data tables.",
"(probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do better #",
"= sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two assignents to review and stufy",
"dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's",
"key-value pairs, i.e. a dictionary! # Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character})",
"If colab not locally Find out the IP address of this Colab Instance",
"and PostgreSQL has in my opinion extra steps so its harder. \"\"\" \"\"\"first",
"# !curl ipecho.net/plain \"\"\" \"How was working with MongoDB different from working with",
"pymongo and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this! Reset it if it",
"it if it leak User = 'John-Thomas' dbname = 'test' connection = (",
"= 'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first",
"harder?\": -MongoDB and PostgrSQL biggest difference is hpw the data/information is stored. -In",
"'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our",
"are used to connect to individual data tables. MongoDB formats and stores the",
"'rpg_character'})) # Our goal - copy the charactercreator_character table get_characters = 'SELECT *",
"is stored. -In PostgreSQL there are schemas that are used to connect to",
"shell and install pymongo and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this! Reset",
"afternoon project rpg_character = (1, \"<NAME>\", 10, 3, 0, 0, 0) # We",
"- annotate type so we can query on it rpg_doc = { 'doc_type':",
"'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'}))",
"to connect to individual data tables. MongoDB formats and stores the all the",
"data/information is stored. -In PostgreSQL there are schemas that are used to connect",
"1}) # 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1",
"rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do better # Mongo doesn't force us",
"= pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's figure out inserting some data",
"0) # We need key-value pairs, i.e. a dictionary! # Lazy way (probably",
"# If colab not locally Find out the IP address of this Colab",
"it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level':",
"there are schemas that are used to connect to individual data tables. MongoDB",
"can do better # Mongo doesn't force us to have a schema, but",
"3})) # Make our doc better - annotate type so we can query",
"doc better - annotate type so we can query on it rpg_doc =",
"'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type':",
"type so we can query on it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key':",
"has in my opinion extra steps so its harder. \"\"\" \"\"\"first make shell",
"seems simpler/easier way to store data and PostgreSQL has in my opinion extra",
"client = pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's figure out inserting some",
"stores the all the data formated in documents. The two have unique differences",
"colab not locally Find out the IP address of this Colab Instance #",
"in my opinon MongoDB seems simpler/easier way to store data and PostgreSQL has",
"# 1 # Let's start the afternoon project rpg_character = (1, \"<NAME>\", 10,",
"was working with MongoDB different from working with PostgreSQL? What was easier, and",
"in my opinion extra steps so its harder. \"\"\" \"\"\"first make shell and",
"# We need key-value pairs, i.e. a dictionary! # Lazy way (probably not",
"schema, but # we *should* try to choose useful/informative key names rpg_doc =",
"and what was harder?\": -MongoDB and PostgrSQL biggest difference is hpw the data/information",
"documents. The two have unique differences and but in my opinon MongoDB seems",
"doesn't force us to have a schema, but # we *should* try to",
"list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy the charactercreator_character table get_characters = 'SELECT",
"'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) # Make our doc better - annotate",
"PostgrSQL biggest difference is hpw the data/information is stored. -In PostgreSQL there are",
"characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two assignents to review and",
"rpg_character = (1, \"<NAME>\", 10, 3, 0, 0, 0) # We need key-value",
"locally Find out the IP address of this Colab Instance # !curl ipecho.net/plain",
"with PostgreSQL? What was easier, and what was harder?\": -MongoDB and PostgrSQL biggest",
"used to connect to individual data tables. MongoDB formats and stores the all",
"+ \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection) db = client.test",
"3, 0, 0, 0) # We need key-value pairs, i.e. a dictionary! #",
"'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) #",
"the data/information is stored. -In PostgreSQL there are schemas that are used to",
"key names rpg_doc = { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3]",
"and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this! Reset it if it leak",
"pymongo.MongoClient(connection) db = client.test dir(db.test) # Let's figure out inserting some data db.test.count_documents({'x':",
"way to store data and PostgreSQL has in my opinion extra steps so",
"so we can query on it rpg_doc = { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0],",
"have unique differences and but in my opinon MongoDB seems simpler/easier way to",
"to have a schema, but # we *should* try to choose useful/informative key",
"simpler/easier way to store data and PostgreSQL has in my opinion extra steps",
"= { 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level':",
"# 0 db.test.insert_one({'x': 1}) # <pymongo.results.InsertOneResult at 0x7f52ad9fd208> db.test.count_documents({'x': 1}) # 1 #",
"different from working with PostgreSQL? What was easier, and what was harder?\": -MongoDB",
"Instance # !curl ipecho.net/plain \"\"\" \"How was working with MongoDB different from working",
"of this Colab Instance # !curl ipecho.net/plain \"\"\" \"How was working with MongoDB",
"install pymongo and dnspython\"\"\" import pymongo password = '<PASSWORD>'commit/share this! Reset it if",
"not locally Find out the IP address of this Colab Instance # !curl",
"password = '<PASSWORD>'commit/share this! Reset it if it leak User = 'John-Thomas' dbname",
"'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal",
"# Let's start the afternoon project rpg_character = (1, \"<NAME>\", 10, 3, 0,",
"\"<NAME>\", 10, 3, 0, 0, 0) # We need key-value pairs, i.e. a",
"Reset it if it leak User = 'John-Thomas' dbname = 'test' connection =",
"PostgreSQL has in my opinion extra steps so its harder. \"\"\" \"\"\"first make",
"\"mongodb+srv://John-Thomas:\" + password + \"@cluster.y2ftp.mongodb.net/\" + dbname + \"?retryWrites=true&w\" \"=majority\") client = pymongo.MongoClient(connection)",
"'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'doc_type': 'rpg_character'})) # Our goal - copy",
"pairs, i.e. a dictionary! # Lazy way (probably not ideal) db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character':",
"to individual data tables. MongoDB formats and stores the all the data formated",
"'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] } db.test.insert_one(rpg_doc) list(db.test.find({'level': 3})) #",
"the all the data formated in documents. The two have unique differences and",
"db.test.insert_one({'rpg_character': rpg_character}) db.test.find_one({'rpg_character': rpg_character}) # We can do better # Mongo doesn't force",
"= { 'doc_type': 'rpg_character', 'sql_key': rpg_character[0], 'name': rpg_character[1], 'hp': rpg_character[2], 'level': rpg_character[3] }",
"get_characters = 'SELECT * FROM charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on",
"stored. -In PostgreSQL there are schemas that are used to connect to individual",
"Our goal - copy the charactercreator_character table get_characters = 'SELECT * FROM charactercreator_character;'",
"tables. MongoDB formats and stores the all the data formated in documents. The",
"charactercreator_character;' characters = sl_curs.execute(get_characters).fetchall() characters[:10] # worked on first two assignents to review",
"individual data tables. MongoDB formats and stores the all the data formated in",
"Colab Instance # !curl ipecho.net/plain \"\"\" \"How was working with MongoDB different from",
"\"How was working with MongoDB different from working with PostgreSQL? What was easier,",
"project rpg_character = (1, \"<NAME>\", 10, 3, 0, 0, 0) # We need",
"that are used to connect to individual data tables. MongoDB formats and stores"
] |
[
"age = int(input (\"Combien d'année à votre chien ?\\n\")) ageVrai = age*7 print",
"= int(input (\"Combien d'année à votre chien ?\\n\")) ageVrai = age*7 print (f\"Votre",
"à votre chien ?\\n\")) ageVrai = age*7 print (f\"Votre chien a {ageVrai} ans.\")",
"d'année à votre chien ?\\n\")) ageVrai = age*7 print (f\"Votre chien a {ageVrai}",
"(\"Combien d'année à votre chien ?\\n\")) ageVrai = age*7 print (f\"Votre chien a",
"int(input (\"Combien d'année à votre chien ?\\n\")) ageVrai = age*7 print (f\"Votre chien"
] |
[
"password, if an account exists with the email you entered. You should receive",
"login, logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls import",
"= UserLogin return render(request, self.template, locals()) def post(self, request): filled_form = UserLogin(request.POST) if",
"= [item for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list}')",
"messages.success(request, f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no",
"view class Home(View): template = 'general/main_page.html' def get(self, request): return render(request, self.template) #",
"= <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user} !!') login(request,",
"handling class Register(View): template = 'general/login_page.html' def get(self, request): empty_form = UserRegistration return",
"UserRegistration from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.views",
"get(self, request): empty_form = UserLogin return render(request, self.template, locals()) def post(self, request): filled_form",
"setting your password, if an account exists with the email you entered. You",
"f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such",
"from .forms import UserLogin, UserRegistration from django.contrib import messages from django.contrib.auth import authenticate,",
"something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def",
"messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()]",
"something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def",
"template = 'general/main_page.html' def get(self, request): return render(request, self.template) # Login handling class",
"= filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: messages.success(request, f'Hello",
"wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return",
"# Logout handling class Logout(View): def get(self, request): logout(request) return redirect('Home') # Register",
"you registered with,and check your spam folder.''') return str(self.request.META.get('HTTP_REFERER')) # success_url may be",
"import render, redirect from django.views import View from .forms import UserLogin, UserRegistration from",
"else: messages.error(request, 'There is no such username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else:",
"class Register(View): template = 'general/login_page.html' def get(self, request): empty_form = UserRegistration return render(request,",
"filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url",
"from django.urls import reverse_lazy # Main page view class Home(View): template = 'general/main_page.html'",
"to redirect to after processing a valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No",
"you entered. You should receive them shortly. \\n If you don't receive an",
"error_list = [item for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n",
"redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to redirect",
"account exists with the email you entered. You should receive them shortly. \\n",
"get(self, request): return render(request, self.template) # Login handling class Login(View): template = 'general/login_page.html'",
"Register handling class Register(View): template = 'general/login_page.html' def get(self, request): empty_form = UserRegistration",
"filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user}",
"\\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def get(self, request): logout(request)",
"return render(request, self.template, locals()) def post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username",
"request): empty_form = UserRegistration return render(request, self.template, locals()) def post(self, request): filled_form =",
"filled_form = UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user =",
"request): empty_form = UserLogin return render(request, self.template, locals()) def post(self, request): filled_form =",
"messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class",
"def get(self, request): empty_form = UserRegistration return render(request, self.template, locals()) def post(self, request):",
"class Login(View): template = 'general/login_page.html' def get(self, request): empty_form = UserLogin return render(request,",
"if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if",
"redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def get(self, request): logout(request) return redirect('Home') #",
"= 'general/login_page.html' def get(self, request): empty_form = UserRegistration return render(request, self.template, locals()) def",
"{error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL",
"success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to redirect to after processing",
"get_success_url(self): \"\"\"Return the URL to redirect to after processing a valid form.\"\"\" if",
"render, redirect from django.views import View from .forms import UserLogin, UserRegistration from django.contrib",
"from django.contrib.auth import authenticate, login, logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions import",
"went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def get(self,",
"return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()] messages.error(request, f'Upps something",
"messages.info(self.request, '''We've emailed you instructions for setting your password, if an account exists",
"import ImproperlyConfigured from django.urls import reverse_lazy # Main page view class Home(View): template",
"locals()) def post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!')",
"f'Upps something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done')",
"\\n If you don't receive an email, please make sure you've entered the",
"for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER'))",
"render(request, self.template, locals()) def post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username =",
"render(request, self.template) # Login handling class Login(View): template = 'general/login_page.html' def get(self, request):",
"processing a valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL to redirect to.",
"emailed you instructions for setting your password, if an account exists with the",
"an account exists with the email you entered. You should receive them shortly.",
"= UserRegistration return render(request, self.template, locals()) def post(self, request): filled_form = UserRegistration(request.POST) if",
"django.contrib.auth import authenticate, login, logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured",
"'general/main_page.html' def get(self, request): return render(request, self.template) # Login handling class Login(View): template",
"Main page view class Home(View): template = 'general/main_page.html' def get(self, request): return render(request,",
"= authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER'))",
"success_url.\") else: messages.info(self.request, '''We've emailed you instructions for setting your password, if an",
"don't receive an email, please make sure you've entered the address you registered",
"request): return render(request, self.template) # Login handling class Login(View): template = 'general/login_page.html' def",
"'general/login_page.html' def get(self, request): empty_form = UserRegistration return render(request, self.template, locals()) def post(self,",
"django.views import View from .forms import UserLogin, UserRegistration from django.contrib import messages from",
"not self.success_url: raise ImproperlyConfigured(\"No URL to redirect to. Provide a success_url.\") else: messages.info(self.request,",
"ImproperlyConfigured from django.urls import reverse_lazy # Main page view class Home(View): template =",
"in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView):",
"form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL to redirect to. Provide a success_url.\")",
"redirect to after processing a valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL",
"redirect('Home') # Register handling class Register(View): template = 'general/login_page.html' def get(self, request): empty_form",
"return redirect('Home') # Register handling class Register(View): template = 'general/login_page.html' def get(self, request):",
"Login handling class Login(View): template = 'general/login_page.html' def get(self, request): empty_form = UserLogin",
"item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) #",
"else: messages.info(self.request, '''We've emailed you instructions for setting your password, if an account",
"them shortly. \\n If you don't receive an email, please make sure you've",
"template = 'general/login_page.html' def get(self, request): empty_form = UserRegistration return render(request, self.template, locals())",
"locals()) def post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password",
"username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: messages.success(request,",
"if not self.success_url: raise ImproperlyConfigured(\"No URL to redirect to. Provide a success_url.\") else:",
"login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such username in the",
"class Home(View): template = 'general/main_page.html' def get(self, request): return render(request, self.template) # Login",
"username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in",
"the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()] messages.error(request,",
"Register(View): template = 'general/login_page.html' def get(self, request): empty_form = UserRegistration return render(request, self.template,",
"your password, if an account exists with the email you entered. You should",
"ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to redirect to after",
"= UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username,",
"def post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password =",
"get(self, request): logout(request) return redirect('Home') # Register handling class Register(View): template = 'general/login_page.html'",
"empty_form = UserRegistration return render(request, self.template, locals()) def post(self, request): filled_form = UserRegistration(request.POST)",
"{error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def get(self, request): logout(request) return",
"went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self):",
"receive them shortly. \\n If you don't receive an email, please make sure",
"You should receive them shortly. \\n If you don't receive an email, please",
"URL to redirect to. Provide a success_url.\") else: messages.info(self.request, '''We've emailed you instructions",
"django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.views import PasswordResetView",
"= 'general/main_page.html' def get(self, request): return render(request, self.template) # Login handling class Login(View):",
"you've entered the address you registered with,and check your spam folder.''') return str(self.request.META.get('HTTP_REFERER'))",
"Provide a success_url.\") else: messages.info(self.request, '''We've emailed you instructions for setting your password,",
"filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item",
"\"\"\"Return the URL to redirect to after processing a valid form.\"\"\" if not",
"no such username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for",
"filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in",
"the address you registered with,and check your spam folder.''') return str(self.request.META.get('HTTP_REFERER')) # success_url",
"return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def get(self, request): logout(request) return redirect('Home')",
"class Logout(View): def get(self, request): logout(request) return redirect('Home') # Register handling class Register(View):",
"user: messages.success(request, f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is",
"redirect to. Provide a success_url.\") else: messages.info(self.request, '''We've emailed you instructions for setting",
"if an account exists with the email you entered. You should receive them",
"If you don't receive an email, please make sure you've entered the address",
"should receive them shortly. \\n If you don't receive an email, please make",
"class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to redirect to",
"messages.error(request, 'There is no such username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list",
"from django.shortcuts import render, redirect from django.views import View from .forms import UserLogin,",
"# Register handling class Register(View): template = 'general/login_page.html' def get(self, request): empty_form =",
"make sure you've entered the address you registered with,and check your spam folder.''')",
"email, please make sure you've entered the address you registered with,and check your",
"import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.views import PasswordResetView from",
"wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View): def get(self, request):",
"self.template, locals()) def post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User",
"render(request, self.template, locals()) def post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request,",
"page view class Home(View): template = 'general/main_page.html' def get(self, request): return render(request, self.template)",
"registered with,and check your spam folder.''') return str(self.request.META.get('HTTP_REFERER')) # success_url may be lazy",
"post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password')",
"UserLogin return render(request, self.template, locals()) def post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid():",
"a valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL to redirect to. Provide",
"# Login handling class Login(View): template = 'general/login_page.html' def get(self, request): empty_form =",
"get(self, request): empty_form = UserRegistration return render(request, self.template, locals()) def post(self, request): filled_form",
"valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL to redirect to. Provide a",
"instructions for setting your password, if an account exists with the email you",
"Logout(View): def get(self, request): logout(request) return redirect('Home') # Register handling class Register(View): template",
"return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to",
"exists with the email you entered. You should receive them shortly. \\n If",
"to. Provide a success_url.\") else: messages.info(self.request, '''We've emailed you instructions for setting your",
"logout(request) return redirect('Home') # Register handling class Register(View): template = 'general/login_page.html' def get(self,",
"Home(View): template = 'general/main_page.html' def get(self, request): return render(request, self.template) # Login handling",
"= reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to redirect to after processing a",
"raise ImproperlyConfigured(\"No URL to redirect to. Provide a success_url.\") else: messages.info(self.request, '''We've emailed",
"= [item for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}')",
"import authenticate, login, logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured from",
"in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()]",
"def get(self, request): return render(request, self.template) # Login handling class Login(View): template =",
"'There is no such username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list =",
"shortly. \\n If you don't receive an email, please make sure you've entered",
"import UserLogin, UserRegistration from django.contrib import messages from django.contrib.auth import authenticate, login, logout",
"import View from .forms import UserLogin, UserRegistration from django.contrib import messages from django.contrib.auth",
"request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user",
"!!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such username in",
"email you entered. You should receive them shortly. \\n If you don't receive",
"Login(View): template = 'general/login_page.html' def get(self, request): empty_form = UserLogin return render(request, self.template,",
"database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()] messages.error(request, f'Upps",
"def get_success_url(self): \"\"\"Return the URL to redirect to after processing a valid form.\"\"\"",
"import reverse_lazy # Main page view class Home(View): template = 'general/main_page.html' def get(self,",
"django.urls import reverse_lazy # Main page view class Home(View): template = 'general/main_page.html' def",
"password=password) if user: messages.success(request, f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request,",
"reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the URL to redirect to after processing a valid",
"<PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user} !!') login(request, user)",
"for setting your password, if an account exists with the email you entered.",
"django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy # Main page view class Home(View):",
"PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy # Main page view",
"Logout handling class Logout(View): def get(self, request): logout(request) return redirect('Home') # Register handling",
"django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy # Main",
"else: error_list = [item for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!!",
"redirect from django.views import View from .forms import UserLogin, UserRegistration from django.contrib import",
"redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such username in the database!') return redirect(self.request.META.get('HTTP_REFERER'))",
"post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER'))",
"request): logout(request) return redirect('Home') # Register handling class Register(View): template = 'general/login_page.html' def",
"reverse_lazy # Main page view class Home(View): template = 'general/main_page.html' def get(self, request):",
"item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class",
"import PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy # Main page",
"user = authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user} !!') login(request, user) return",
"self.template, locals()) def post(self, request): filled_form = UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field')",
"sure you've entered the address you registered with,and check your spam folder.''') return",
"you don't receive an email, please make sure you've entered the address you",
".forms import UserLogin, UserRegistration from django.contrib import messages from django.contrib.auth import authenticate, login,",
"after processing a valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL to redirect",
"UserRegistration return render(request, self.template, locals()) def post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid():",
"UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item",
"from django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy #",
"redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()] messages.error(request, f'Upps something went",
"in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout",
"return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such username in the database!') return",
"# Main page view class Home(View): template = 'general/main_page.html' def get(self, request): return",
"if user: messages.success(request, f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There",
"is no such username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item",
"from django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy # Main page view class",
"if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for",
"URL to redirect to after processing a valid form.\"\"\" if not self.success_url: raise",
"from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.views import",
"please make sure you've entered the address you registered with,and check your spam",
"self.success_url: raise ImproperlyConfigured(\"No URL to redirect to. Provide a success_url.\") else: messages.info(self.request, '''We've",
"authenticate, login, logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls",
"request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else:",
"from django.views import View from .forms import UserLogin, UserRegistration from django.contrib import messages",
"UserLogin, UserRegistration from django.contrib import messages from django.contrib.auth import authenticate, login, logout from",
"to redirect to. Provide a success_url.\") else: messages.info(self.request, '''We've emailed you instructions for",
"self.template) # Login handling class Login(View): template = 'general/login_page.html' def get(self, request): empty_form",
"entered. You should receive them shortly. \\n If you don't receive an email,",
"entered the address you registered with,and check your spam folder.''') return str(self.request.META.get('HTTP_REFERER')) #",
"return render(request, self.template, locals()) def post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save()",
"the email you entered. You should receive them shortly. \\n If you don't",
"UserLogin(request.POST) if filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password)",
"return render(request, self.template) # Login handling class Login(View): template = 'general/login_page.html' def get(self,",
"messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions",
"= 'general/login_page.html' def get(self, request): empty_form = UserLogin return render(request, self.template, locals()) def",
"the URL to redirect to after processing a valid form.\"\"\" if not self.success_url:",
"ImproperlyConfigured(\"No URL to redirect to. Provide a success_url.\") else: messages.info(self.request, '''We've emailed you",
"'''We've emailed you instructions for setting your password, if an account exists with",
"logout from django.contrib.auth.views import PasswordResetView from django.core.exceptions import ImproperlyConfigured from django.urls import reverse_lazy",
"authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else:",
"def get(self, request): empty_form = UserLogin return render(request, self.template, locals()) def post(self, request):",
"handling class Logout(View): def get(self, request): logout(request) return redirect('Home') # Register handling class",
"password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: messages.success(request, f'Hello {user} !!')",
"with the email you entered. You should receive them shortly. \\n If you",
"View from .forms import UserLogin, UserRegistration from django.contrib import messages from django.contrib.auth import",
"'general/login_page.html' def get(self, request): empty_form = UserLogin return render(request, self.template, locals()) def post(self,",
"receive an email, please make sure you've entered the address you registered with,and",
"an email, please make sure you've entered the address you registered with,and check",
"address you registered with,and check your spam folder.''') return str(self.request.META.get('HTTP_REFERER')) # success_url may",
"you instructions for setting your password, if an account exists with the email",
"def post(self, request): filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return",
"\\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url = reverse_lazy('password_reset_done') def get_success_url(self): \"\"\"Return the",
"a success_url.\") else: messages.info(self.request, '''We've emailed you instructions for setting your password, if",
"[item for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}') return",
"= UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list =",
"such username in the database!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item",
"for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER'))",
"'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()] messages.error(request,",
"to after processing a valid form.\"\"\" if not self.success_url: raise ImproperlyConfigured(\"No URL to",
"f'Upps something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling class Logout(View):",
"handling class Login(View): template = 'general/login_page.html' def get(self, request): empty_form = UserLogin return",
"created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list = [item for item in filled_form.errors.values()] messages.error(request, f'Upps",
"empty_form = UserLogin return render(request, self.template, locals()) def post(self, request): filled_form = UserLogin(request.POST)",
"user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such username in the database!')",
"[item for item in filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list}') return",
"django.shortcuts import render, redirect from django.views import View from .forms import UserLogin, UserRegistration",
"def get(self, request): logout(request) return redirect('Home') # Register handling class Register(View): template =",
"filled_form.is_valid(): username = filled_form.cleaned_data.get('username_field') password = <PASSWORD>_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user:",
"filled_form.errors.values()] messages.error(request, f'Upps something went wrong!! \\n {error_list[0]}') return redirect(self.request.META.get('HTTP_REFERER')) # Logout handling",
"messages.error(request, f'Upps something went wrong!! \\n {error_list}') return redirect(self.request.META.get('HTTP_REFERER')) class ModifiedPasswordResetView(PasswordResetView): success_url =",
"template = 'general/login_page.html' def get(self, request): empty_form = UserLogin return render(request, self.template, locals())",
"filled_form = UserRegistration(request.POST) if filled_form.is_valid(): filled_form.save() messages.success(request, 'User created!') return redirect(self.request.META.get('HTTP_REFERER')) else: error_list",
"{user} !!') login(request, user) return redirect(self.request.META.get('HTTP_REFERER')) else: messages.error(request, 'There is no such username"
] |
[
"scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new, scale_trils # This is",
"\"\"\"Initializes a dynamics model for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 #",
"nn import torchfilter import torchfilter.types as types from fannypack.nn import resblocks from .",
"= nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build neural network self.state_layers =",
"final state output state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update =",
"produce our final state output state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:])",
"for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril",
"state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new, scale_trils # This",
"2) state_features = self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features, state_features), dim=-1) #",
"neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units *",
"class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\"",
"= torch.cat((control_features, state_features), dim=-1) # (N, units * 2) => (N, state_dim +",
"state_features), dim=-1) # (N, units * 2) => (N, state_dim + 1) output_features",
"layers # TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes",
"= output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate #",
"dim=-1) # (N, units * 2) => (N, state_dim + 1) output_features =",
"(N, control_dim) => (N, units // 2) control_features = self.control_layers(controls) # (N, state_dim)",
"make learning # the noise model easier. # # Separate because the checkpoint",
"= nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, ) # Build neural network",
"torch import torch.nn as nn import torchfilter import torchfilter.types as types from fannypack.nn",
"above, but with the noise tweaked/parameterized to make learning # the noise model",
"control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01]))",
"layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units),",
") # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers =",
"= self.shared_layers(merged_features) # We separately compute a direction for our network and a",
":, :].expand(N, state_dim, state_dim) return states_new, scale_trils # This is the same as",
"noise tweaked/parameterized to make learning # the noise model easier. # # Separate",
"dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, ) #",
"class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\"",
"# TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a",
"// 2) state_features = self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features, state_features), dim=-1)",
"types.ControlsTorch, ) -> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim == self.state_dim #",
"a direction for our network and a scalar \"gate\" # These are multiplied",
"# to just casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64):",
"types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim ==",
"our network and a scalar \"gate\" # These are multiplied to produce our",
"are multiplied to produce our final state output state_update_direction = output_features[..., :state_dim] state_update_gate",
"import layers # TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64):",
"self.shared_layers = nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim +",
"(N, units * 2) => (N, state_dim + 1) output_features = self.shared_layers(merged_features) #",
"nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units",
"torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, ) # Build neural network self.state_layers =",
"= layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units),",
"initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N, state_dim, state_dim ) return",
"fannypack.nn import resblocks from . import layers # TODO: Merge this with DoorDynamicsModelBrent",
"import torch.nn as nn import torchfilter import torchfilter.types as types from fannypack.nn import",
"import resblocks from . import layers # TODO: Merge this with DoorDynamicsModelBrent class",
"= 7 # Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) /",
"# Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) #",
"covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build neural network",
"from . import layers # TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def",
"0.01]))), requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units)",
"nn.Linear(units, self.state_dim + 1), ) self.units = units def forward( self, *, initial_states:",
"2) control_features = self.control_layers(controls) # (N, state_dim) => (N, units // 2) state_features",
"self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, ) # Build neural",
"units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units = units def",
"= torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate # Return residual-style state update,",
"self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new, scale_trils # This is the same",
"casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics",
"(N, units) merged_features = torch.cat((control_features, state_features), dim=-1) # (N, units * 2) =>",
"nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model",
"// 2) control_features = self.control_layers(controls) # (N, state_dim) => (N, units // 2)",
"self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim = initial_states.shape[:2]",
"# Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False,",
"DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\" super().__init__(state_dim=3)",
"= initial_states.shape[:2] assert state_dim == self.state_dim # (N, control_dim) => (N, units //",
"control_features = self.control_layers(controls) # (N, state_dim) => (N, units // 2) state_features =",
"self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2, units),",
"# Return residual-style state update, constant uncertainties states_new = initial_states + state_update scale_trils",
"We separately compute a direction for our network and a scalar \"gate\" #",
"state_dim == self.state_dim # (N, control_dim) => (N, units // 2) control_features =",
"constant uncertainties states_new = initial_states + state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim,",
"no longer be compatible, and we don't want # to just casually nuke",
"-> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim == self.state_dim # (N, control_dim)",
"state update, constant uncertainties states_new = initial_states + state_update scale_trils = self.Q_scale_tril[None, :,",
"7 # Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, )",
"merged_features = torch.cat((control_features, state_features), dim=-1) # (N, units * 2) => (N, state_dim",
"# These are multiplied to produce our final state output state_update_direction = output_features[...,",
"scale_trils # This is the same as above, but with the noise tweaked/parameterized",
"== self.state_dim # (N, control_dim) => (N, units // 2) control_features = self.control_layers(controls)",
"state_dim + 1) output_features = self.shared_layers(merged_features) # We separately compute a direction for",
"controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim == self.state_dim",
"forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim =",
"*, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert",
"update, constant uncertainties states_new = initial_states + state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N,",
"state_features = self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features, state_features), dim=-1) # (N,",
"= nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1),",
"+ state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N, state_dim, state_dim ) return states_new,",
"a scalar \"gate\" # These are multiplied to produce our final state output",
"to just casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes",
"=> (N, state_dim + 1) output_features = self.shared_layers(merged_features) # We separately compute a",
"dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build neural",
"output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate # Return",
"state_update_direction * state_update_gate # Return residual-style state update, constant uncertainties states_new = initial_states",
"state_dim, state_dim) return states_new, scale_trils # This is the same as above, but",
"we don't want # to just casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel):",
") self.units = units def forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, )",
"* 2) => (N, state_dim + 1) output_features = self.shared_layers(merged_features) # We separately",
"is the same as above, but with the noise tweaked/parameterized to make learning",
"0.01, 0.01])) / 8.0, requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units)",
"* state_update_gate # Return residual-style state update, constant uncertainties states_new = initial_states +",
"door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril = nn.Parameter(",
"because the checkpoint files will no longer be compatible, and we don't want",
"output_features = self.shared_layers(merged_features) # We separately compute a direction for our network and",
"torch.nn as nn import torchfilter import torchfilter.types as types from fannypack.nn import resblocks",
"super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01,",
"DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door",
"resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units = units def forward( self, *,",
"# class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door",
"noise model easier. # # Separate because the checkpoint files will no longer",
"= state_update_direction * state_update_gate # Return residual-style state update, constant uncertainties states_new =",
"residual-style state update, constant uncertainties states_new = initial_states + state_update scale_trils = self.Q_scale_tril[None,",
"nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), )",
"These are multiplied to produce our final state output state_update_direction = output_features[..., :state_dim]",
"as nn import torchfilter import torchfilter.types as types from fannypack.nn import resblocks from",
"units def forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N,",
"=> (N, units // 2) state_features = self.state_layers(initial_states) # (N, units) merged_features =",
"= self.control_layers(controls) # (N, state_dim) => (N, units // 2) state_features = self.state_layers(initial_states)",
"assert state_dim == self.state_dim # (N, control_dim) => (N, units // 2) control_features",
"= initial_states + state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new,",
"compatible, and we don't want # to just casually nuke Michelle's models... #",
"just casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a",
"compute a direction for our network and a scalar \"gate\" # These are",
"for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril_diag",
"# the noise model easier. # # Separate because the checkpoint files will",
"control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))),",
"easier. # # Separate because the checkpoint files will no longer be compatible,",
"DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\" super().__init__(state_dim=3)",
"this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for",
"Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build",
"requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers",
"1) output_features = self.shared_layers(merged_features) # We separately compute a direction for our network",
"# We separately compute a direction for our network and a scalar \"gate\"",
"resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units = units def forward(",
"for our network and a scalar \"gate\" # These are multiplied to produce",
"model for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance",
"# (N, units) merged_features = torch.cat((control_features, state_features), dim=-1) # (N, units * 2)",
"resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units = units def forward( self,",
"2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units = units",
"self.control_layers(controls) # (N, state_dim) => (N, units // 2) state_features = self.state_layers(initial_states) #",
"state_update = state_update_direction * state_update_gate # Return residual-style state update, constant uncertainties states_new",
"uncertainties states_new = initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N, state_dim,",
"states_new = initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N, state_dim, state_dim",
"state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate",
"# Separate because the checkpoint files will no longer be compatible, and we",
"and we don't want # to just casually nuke Michelle's models... # class",
"0.01, 0.01]))), requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers =",
"but with the noise tweaked/parameterized to make learning # the noise model easier.",
"# (N, state_dim) => (N, units // 2) state_features = self.state_layers(initial_states) # (N,",
"state_dim) return states_new, scale_trils # This is the same as above, but with",
"state output state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction",
"from fannypack.nn import resblocks from . import layers # TODO: Merge this with",
"initial_states + state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new, scale_trils",
"the checkpoint files will no longer be compatible, and we don't want #",
"constant uncertainties states_new = initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N,",
"self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build neural network self.state_layers",
"update, constant uncertainties states_new = initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand(",
"(N, state_dim + 1) output_features = self.shared_layers(merged_features) # We separately compute a direction",
"units) merged_features = torch.cat((control_features, state_features), dim=-1) # (N, units * 2) => (N,",
"the same as above, but with the noise tweaked/parameterized to make learning #",
"resblocks from . import layers # TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel):",
"tweaked/parameterized to make learning # the noise model easier. # # Separate because",
"1), ) self.units = units def forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch,",
"and a scalar \"gate\" # These are multiplied to produce our final state",
"super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01,",
"7 # Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0,",
"-1:]) state_update = state_update_direction * state_update_gate # Return residual-style state update, constant uncertainties",
"states_new, scale_trils # This is the same as above, but with the noise",
"as above, but with the noise tweaked/parameterized to make learning # the noise",
"<gh_stars>10-100 import torch import torch.nn as nn import torchfilter import torchfilter.types as types",
"to produce our final state output state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[...,",
"models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our",
"network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2,",
"control_dim) => (N, units // 2) control_features = self.control_layers(controls) # (N, state_dim) =>",
"output state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction *",
"task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05,",
"to make learning # the noise model easier. # # Separate because the",
"units // 2) control_features = self.control_layers(controls) # (N, state_dim) => (N, units //",
"Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, )",
"+ 1), ) self.units = units def forward( self, *, initial_states: types.StatesTorch, controls:",
"layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim",
":].expand(N, state_dim, state_dim) return states_new, scale_trils # This is the same as above,",
"states_new = initial_states + state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return",
"residual-style state update, constant uncertainties states_new = initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None,",
"(N, units // 2) state_features = self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features,",
"0.01])) / 8.0, requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers",
"dynamics model for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics",
"* 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units, self.state_dim + 1), ) self.units =",
"+ state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new, scale_trils #",
"self.units = units def forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) ->",
"8.0, requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units)",
"import torchfilter import torchfilter.types as types from fannypack.nn import resblocks from . import",
"self.state_dim # (N, control_dim) => (N, units // 2) control_features = self.control_layers(controls) #",
"\"gate\" # These are multiplied to produce our final state output state_update_direction =",
"__init__(self, units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\" super().__init__(state_dim=3) control_dim =",
"torch.cat((control_features, state_features), dim=-1) # (N, units * 2) => (N, state_dim + 1)",
"=> (N, units // 2) control_features = self.control_layers(controls) # (N, state_dim) => (N,",
"with the noise tweaked/parameterized to make learning # the noise model easier. #",
"= initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N, state_dim, state_dim )",
"covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, ) # Build",
"want # to just casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self,",
"= units def forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch:",
"be compatible, and we don't want # to just casually nuke Michelle's models...",
"Separate because the checkpoint files will no longer be compatible, and we don't",
"N, state_dim = initial_states.shape[:2] assert state_dim == self.state_dim # (N, control_dim) => (N,",
"# # Separate because the checkpoint files will no longer be compatible, and",
"multiplied to produce our final state output state_update_direction = output_features[..., :state_dim] state_update_gate =",
"# (N, control_dim) => (N, units // 2) control_features = self.control_layers(controls) # (N,",
"self.state_dim + 1), ) self.units = units def forward( self, *, initial_states: types.StatesTorch,",
"direction for our network and a scalar \"gate\" # These are multiplied to",
"self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units),",
"This is the same as above, but with the noise tweaked/parameterized to make",
"learning # the noise model easier. # # Separate because the checkpoint files",
"torchfilter import torchfilter.types as types from fannypack.nn import resblocks from . import layers",
"nn.Parameter( torch.sqrt(torch.FloatTensor([0.05, 0.01, 0.01])) / 8.0, requires_grad=False, ) # Build neural network self.state_layers",
"= self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim) return states_new, scale_trils # This is the",
"Return residual-style state update, constant uncertainties states_new = initial_states + state_update scale_trils =",
"return states_new, scale_trils # This is the same as above, but with the",
"2) => (N, state_dim + 1) output_features = self.shared_layers(merged_features) # We separately compute",
") -> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim == self.state_dim # (N,",
"initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim",
"longer be compatible, and we don't want # to just casually nuke Michelle's",
"Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model",
"torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate # Return residual-style state update, constant",
"the noise tweaked/parameterized to make learning # the noise model easier. # #",
"import torch import torch.nn as nn import torchfilter import torchfilter.types as types from",
"with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for our",
"torchfilter.types as types from fannypack.nn import resblocks from . import layers # TODO:",
"units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7",
"/ 8.0, requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers =",
"initial_states.shape[:2] assert state_dim == self.state_dim # (N, control_dim) => (N, units // 2)",
"# Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential(",
"a dynamics model for our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed",
"units // 2) state_features = self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features, state_features),",
"import torchfilter.types as types from fannypack.nn import resblocks from . import layers #",
"TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics",
"def __init__(self, units=64): \"\"\"Initializes a dynamics model for our door task.\"\"\" super().__init__(state_dim=3) control_dim",
"same as above, but with the noise tweaked/parameterized to make learning # the",
"self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features, state_features), dim=-1) # (N, units *",
"= 7 # Fixed dynamics covariance self.Q_scale_tril = nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False,",
"def forward( self, *, initial_states: types.StatesTorch, controls: types.ControlsTorch, ) -> types.StatesTorch: N, state_dim",
"the noise model easier. # # Separate because the checkpoint files will no",
"torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers",
"don't want # to just casually nuke Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def",
"our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril_diag =",
"types from fannypack.nn import resblocks from . import layers # TODO: Merge this",
"state_dim = initial_states.shape[:2] assert state_dim == self.state_dim # (N, control_dim) => (N, units",
"= self.state_layers(initial_states) # (N, units) merged_features = torch.cat((control_features, state_features), dim=-1) # (N, units",
"task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter( torch.sqrt(torch.FloatTensor([0.05,",
"as types from fannypack.nn import resblocks from . import layers # TODO: Merge",
"files will no longer be compatible, and we don't want # to just",
"units * 2) => (N, state_dim + 1) output_features = self.shared_layers(merged_features) # We",
"(N, state_dim) => (N, units // 2) state_features = self.state_layers(initial_states) # (N, units)",
"self.shared_layers(merged_features) # We separately compute a direction for our network and a scalar",
"separately compute a direction for our network and a scalar \"gate\" # These",
"uncertainties states_new = initial_states + state_update scale_trils = self.Q_scale_tril[None, :, :].expand(N, state_dim, state_dim)",
"scalar \"gate\" # These are multiplied to produce our final state output state_update_direction",
"will no longer be compatible, and we don't want # to just casually",
"our door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril =",
"door task.\"\"\" super().__init__(state_dim=3) control_dim = 7 # Fixed dynamics covariance self.Q_scale_tril_diag = nn.Parameter(",
"network and a scalar \"gate\" # These are multiplied to produce our final",
"state update, constant uncertainties states_new = initial_states + state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :,",
"+ 1) output_features = self.shared_layers(merged_features) # We separately compute a direction for our",
":state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate # Return residual-style",
"# This is the same as above, but with the noise tweaked/parameterized to",
"types.StatesTorch: N, state_dim = initial_states.shape[:2] assert state_dim == self.state_dim # (N, control_dim) =>",
"# (N, units * 2) => (N, state_dim + 1) output_features = self.shared_layers(merged_features)",
". import layers # TODO: Merge this with DoorDynamicsModelBrent class DoorDynamicsModel(torchfilter.base.DynamicsModel): def __init__(self,",
"(N, units // 2) control_features = self.control_layers(controls) # (N, state_dim) => (N, units",
"state_update scale_trils = torch.diag(self.Q_scale_tril_diag)[None, :, :].expand( N, state_dim, state_dim ) return states_new, scale_trils",
"state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update = state_update_direction * state_update_gate # Return residual-style state",
"Build neural network self.state_layers = layers.state_layers(units=units) self.control_layers = layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units",
"nn.Parameter( torch.cholesky(torch.diag(torch.FloatTensor([0.05, 0.01, 0.01]))), requires_grad=False, ) # Build neural network self.state_layers = layers.state_layers(units=units)",
"our final state output state_update_direction = output_features[..., :state_dim] state_update_gate = torch.sigmoid(output_features[..., -1:]) state_update",
"checkpoint files will no longer be compatible, and we don't want # to",
"Michelle's models... # class DoorDynamicsModelBrent(torchfilter.base.DynamicsModel): def __init__(self, units=64): \"\"\"Initializes a dynamics model for",
"state_dim) => (N, units // 2) state_features = self.state_layers(initial_states) # (N, units) merged_features",
"model easier. # # Separate because the checkpoint files will no longer be",
"state_update_gate # Return residual-style state update, constant uncertainties states_new = initial_states + state_update",
"= layers.control_layers(units=units) self.shared_layers = nn.Sequential( nn.Linear(units * 2, units), resblocks.Linear(units), resblocks.Linear(units), resblocks.Linear(units), nn.Linear(units,"
] |
[] |
[
"field ' 'is not supported. Nested relationship ' 'inclusions are not currently supported'",
"an array of fields to include. \"\"\" rels = model.relationships params = req.get_param_as_list('include')",
"in the response according to one or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\"",
"InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure the include",
"compound ' 'document.' % param, 'links': LINK, 'parameter': PARAM, }) def init(req, model):",
"the response according to one or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from",
"to one or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams",
"are not currently supported' % param, 'links': LINK, 'parameter': PARAM, }) def _validate_rels(param,",
"field is not a nested relationship \"\"\" if '.' in param: raise InvalidQueryParams(**{",
"'inclusions are not currently supported' % param, 'links': LINK, 'parameter': PARAM, }) def",
"goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure",
"'include' def _validate_no_nesting(param): \"\"\" Ensure the include field is not a nested relationship",
"if param not in rels: raise InvalidQueryParams(**{ 'detail': 'The include query param of",
"LINK, 'parameter': PARAM, }) def init(req, model): \"\"\" Return an array of fields",
"= [param.lower() for param in params] for param in params: _validate_no_nesting(param) _validate_rels(param, rels)",
"import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure the",
"LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure the include field",
"here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include'",
"include field is a relationship \"\"\" if param not in rels: raise InvalidQueryParams(**{",
"the include field is not a nested relationship \"\"\" if '.' in param:",
"model): \"\"\" Return an array of fields to include. \"\"\" rels = model.relationships",
"to include in the response according to one or more criteria. Documented here:",
"a ' 'relationship field & on the primary resource ' '& is not",
"params = [param.lower() for param in params] for param in params: _validate_no_nesting(param) _validate_rels(param,",
"the \"%s\" field ' 'is not possible. It does not represent a '",
"criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM",
"eligible for inclusion as a compound ' 'document.' % param, 'links': LINK, 'parameter':",
"\"\"\" from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param):",
"def init(req, model): \"\"\" Return an array of fields to include. \"\"\" rels",
"% param, 'links': LINK, 'parameter': PARAM, }) def init(req, model): \"\"\" Return an",
"param of the \"%s\" field ' 'is not possible. It does not represent",
"rels: raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\" field '",
"inclusion as a compound ' 'document.' % param, 'links': LINK, 'parameter': PARAM, })",
"~~~~~~~~~~~~~~~~~~~ Determine relationship resources to include in the response according to one or",
"'is not possible. It does not represent a ' 'relationship field & on",
"_validate_no_nesting(param): \"\"\" Ensure the include field is not a nested relationship \"\"\" if",
"jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def",
"'& is not eligible for inclusion as a compound ' 'document.' % param,",
"is a relationship \"\"\" if param not in rels: raise InvalidQueryParams(**{ 'detail': 'The",
"'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure the include field is not",
"' 'is not possible. It does not represent a ' 'relationship field &",
"\"%s\" field ' 'is not possible. It does not represent a ' 'relationship",
"\"\"\" queryparams.include ~~~~~~~~~~~~~~~~~~~ Determine relationship resources to include in the response according to",
"relationship ' 'inclusions are not currently supported' % param, 'links': LINK, 'parameter': PARAM,",
"param, 'links': LINK, 'parameter': PARAM, }) def init(req, model): \"\"\" Return an array",
"not supported. Nested relationship ' 'inclusions are not currently supported' % param, 'links':",
"resource ' '& is not eligible for inclusion as a compound ' 'document.'",
"'document.' % param, 'links': LINK, 'parameter': PARAM, }) def init(req, model): \"\"\" Return",
"Nested relationship ' 'inclusions are not currently supported' % param, 'links': LINK, 'parameter':",
"'The include query param of the \"%s\" field ' 'is not possible. It",
"or [] params = [param.lower() for param in params] for param in params:",
"relationship resources to include in the response according to one or more criteria.",
"supported' % param, 'links': LINK, 'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure",
"Ensure the include field is a relationship \"\"\" if param not in rels:",
"param, 'links': LINK, 'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure the include",
"param: raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\" field '",
"queryparams.include ~~~~~~~~~~~~~~~~~~~ Determine relationship resources to include in the response according to one",
"one or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK",
"'detail': 'The include query param of the \"%s\" field ' 'is not supported.",
"\"\"\" rels = model.relationships params = req.get_param_as_list('include') or [] params = [param.lower() for",
"is not eligible for inclusion as a compound ' 'document.' % param, 'links':",
"\"\"\" Return an array of fields to include. \"\"\" rels = model.relationships params",
"}) def init(req, model): \"\"\" Return an array of fields to include. \"\"\"",
"include query param of the \"%s\" field ' 'is not possible. It does",
"def _validate_rels(param, rels): \"\"\" Ensure the include field is a relationship \"\"\" if",
"InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\" field ' 'is not",
"for inclusion as a compound ' 'document.' % param, 'links': LINK, 'parameter': PARAM,",
"& on the primary resource ' '& is not eligible for inclusion as",
"nested relationship \"\"\" if '.' in param: raise InvalidQueryParams(**{ 'detail': 'The include query",
"not possible. It does not represent a ' 'relationship field & on the",
"\"\"\" if '.' in param: raise InvalidQueryParams(**{ 'detail': 'The include query param of",
"param of the \"%s\" field ' 'is not supported. Nested relationship ' 'inclusions",
"in rels: raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\" field",
"model.relationships params = req.get_param_as_list('include') or [] params = [param.lower() for param in params]",
"= 'include' def _validate_no_nesting(param): \"\"\" Ensure the include field is not a nested",
"' 'is not supported. Nested relationship ' 'inclusions are not currently supported' %",
"LINK, 'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure the include field is",
"field & on the primary resource ' '& is not eligible for inclusion",
"'parameter': PARAM, }) def init(req, model): \"\"\" Return an array of fields to",
"def _validate_no_nesting(param): \"\"\" Ensure the include field is not a nested relationship \"\"\"",
"a nested relationship \"\"\" if '.' in param: raise InvalidQueryParams(**{ 'detail': 'The include",
"from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\"",
"req.get_param_as_list('include') or [] params = [param.lower() for param in params] for param in",
"PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure the include field is not a",
"include query param of the \"%s\" field ' 'is not supported. Nested relationship",
"}) def _validate_rels(param, rels): \"\"\" Ensure the include field is a relationship \"\"\"",
"PARAM, }) def init(req, model): \"\"\" Return an array of fields to include.",
"'is not supported. Nested relationship ' 'inclusions are not currently supported' % param,",
"<gh_stars>1-10 \"\"\" queryparams.include ~~~~~~~~~~~~~~~~~~~ Determine relationship resources to include in the response according",
"It does not represent a ' 'relationship field & on the primary resource",
"'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure the include field is a",
"for param in params] for param in params: _validate_no_nesting(param) _validate_rels(param, rels) return params",
"Determine relationship resources to include in the response according to one or more",
"'The include query param of the \"%s\" field ' 'is not supported. Nested",
"of the \"%s\" field ' 'is not supported. Nested relationship ' 'inclusions are",
"include in the response according to one or more criteria. Documented here: jsonapi.org/format/#fetching-includes",
"_validate_rels(param, rels): \"\"\" Ensure the include field is a relationship \"\"\" if param",
"' 'relationship field & on the primary resource ' '& is not eligible",
"more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes'",
"' 'inclusions are not currently supported' % param, 'links': LINK, 'parameter': PARAM, })",
"\"\"\" Ensure the include field is not a nested relationship \"\"\" if '.'",
"currently supported' % param, 'links': LINK, 'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\"",
"'relationship field & on the primary resource ' '& is not eligible for",
"= req.get_param_as_list('include') or [] params = [param.lower() for param in params] for param",
"include field is not a nested relationship \"\"\" if '.' in param: raise",
"= model.relationships params = req.get_param_as_list('include') or [] params = [param.lower() for param in",
"of fields to include. \"\"\" rels = model.relationships params = req.get_param_as_list('include') or []",
"not eligible for inclusion as a compound ' 'document.' % param, 'links': LINK,",
"is not a nested relationship \"\"\" if '.' in param: raise InvalidQueryParams(**{ 'detail':",
"[param.lower() for param in params] for param in params: _validate_no_nesting(param) _validate_rels(param, rels) return",
"if '.' in param: raise InvalidQueryParams(**{ 'detail': 'The include query param of the",
"to include. \"\"\" rels = model.relationships params = req.get_param_as_list('include') or [] params =",
"field ' 'is not possible. It does not represent a ' 'relationship field",
"a relationship \"\"\" if param not in rels: raise InvalidQueryParams(**{ 'detail': 'The include",
"the primary resource ' '& is not eligible for inclusion as a compound",
"rels): \"\"\" Ensure the include field is a relationship \"\"\" if param not",
"Return an array of fields to include. \"\"\" rels = model.relationships params =",
"relationship \"\"\" if param not in rels: raise InvalidQueryParams(**{ 'detail': 'The include query",
"the \"%s\" field ' 'is not supported. Nested relationship ' 'inclusions are not",
"rels = model.relationships params = req.get_param_as_list('include') or [] params = [param.lower() for param",
"[] params = [param.lower() for param in params] for param in params: _validate_no_nesting(param)",
"init(req, model): \"\"\" Return an array of fields to include. \"\"\" rels =",
"not in rels: raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\"",
"on the primary resource ' '& is not eligible for inclusion as a",
"fields to include. \"\"\" rels = model.relationships params = req.get_param_as_list('include') or [] params",
"Ensure the include field is not a nested relationship \"\"\" if '.' in",
"resources to include in the response according to one or more criteria. Documented",
"' 'document.' % param, 'links': LINK, 'parameter': PARAM, }) def init(req, model): \"\"\"",
"'detail': 'The include query param of the \"%s\" field ' 'is not possible.",
"of the \"%s\" field ' 'is not possible. It does not represent a",
"in param: raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\" field",
"not a nested relationship \"\"\" if '.' in param: raise InvalidQueryParams(**{ 'detail': 'The",
"primary resource ' '& is not eligible for inclusion as a compound '",
"or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK =",
"not represent a ' 'relationship field & on the primary resource ' '&",
"response according to one or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions",
"include. \"\"\" rels = model.relationships params = req.get_param_as_list('include') or [] params = [param.lower()",
"'.' in param: raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\"",
"possible. It does not represent a ' 'relationship field & on the primary",
"array of fields to include. \"\"\" rels = model.relationships params = req.get_param_as_list('include') or",
"'links': LINK, 'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure the include field",
"raise InvalidQueryParams(**{ 'detail': 'The include query param of the \"%s\" field ' 'is",
"field is a relationship \"\"\" if param not in rels: raise InvalidQueryParams(**{ 'detail':",
"query param of the \"%s\" field ' 'is not possible. It does not",
"= 'jsonapi.org/format/#fetching-includes' PARAM = 'include' def _validate_no_nesting(param): \"\"\" Ensure the include field is",
"% param, 'links': LINK, 'parameter': PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure the",
"\"\"\" if param not in rels: raise InvalidQueryParams(**{ 'detail': 'The include query param",
"not currently supported' % param, 'links': LINK, 'parameter': PARAM, }) def _validate_rels(param, rels):",
"\"\"\" Ensure the include field is a relationship \"\"\" if param not in",
"a compound ' 'document.' % param, 'links': LINK, 'parameter': PARAM, }) def init(req,",
"as a compound ' 'document.' % param, 'links': LINK, 'parameter': PARAM, }) def",
"params = req.get_param_as_list('include') or [] params = [param.lower() for param in params] for",
"the include field is a relationship \"\"\" if param not in rels: raise",
"' '& is not eligible for inclusion as a compound ' 'document.' %",
"query param of the \"%s\" field ' 'is not supported. Nested relationship '",
"Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import InvalidQueryParams LINK = 'jsonapi.org/format/#fetching-includes' PARAM =",
"according to one or more criteria. Documented here: jsonapi.org/format/#fetching-includes \"\"\" from goldman.exceptions import",
"supported. Nested relationship ' 'inclusions are not currently supported' % param, 'links': LINK,",
"param not in rels: raise InvalidQueryParams(**{ 'detail': 'The include query param of the",
"\"%s\" field ' 'is not supported. Nested relationship ' 'inclusions are not currently",
"PARAM, }) def _validate_rels(param, rels): \"\"\" Ensure the include field is a relationship",
"represent a ' 'relationship field & on the primary resource ' '& is",
"'links': LINK, 'parameter': PARAM, }) def init(req, model): \"\"\" Return an array of",
"relationship \"\"\" if '.' in param: raise InvalidQueryParams(**{ 'detail': 'The include query param",
"does not represent a ' 'relationship field & on the primary resource '"
] |
[
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"(x + 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask = x",
"KIND, either express or implied. # See the License for the specific language",
"language governing permissions and # limitations under the License. from __future__ import print_function",
"Unless required by applicable law or agreed to in writing, software # distributed",
"get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self):",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype =",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self):",
"class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class",
"relu(out) elif act == 'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\")",
"np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = {",
"128)) } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype =",
"def test_check_output(self): if self.dtype == np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol)",
"self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {'trans_x': True, \"activation\": 'relu'}",
"1e-3 def test_check_output(self): if self.dtype == np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place,",
"self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {'trans_x': True, \"activation\": 'relu'} def",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol =",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5,",
"} self.attrs = {\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none')",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type",
"this file except in compliance with the License. # You may obtain a",
"pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class",
"class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol =",
"y_ref.astype(x.dtype) def relu(x): mask = x > 0 return x * mask def",
"print_function import unittest import numpy as np import paddle import paddle.fluid.core as core",
"get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {'trans_x': True,",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"8, 128)) } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype =",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def",
"paddle.fluid.core as core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref =",
"{ 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self):",
"ANY KIND, either express or implied. # See the License for the specific",
"and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core",
"self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype",
"self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True,",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16):",
"core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype =",
"self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) -",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def",
"class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"- 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs",
"TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out':",
"self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype)",
"self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self):",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16):",
"skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5 * x * ( 1.0 +",
"gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\")",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16):",
"reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"elif act == 'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single",
"CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype",
"CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 if __name__",
"specific language governing permissions and # limitations under the License. from __future__ import",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype =",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single",
"self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self):",
"OF ANY KIND, either express or implied. # See the License for the",
"0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'],",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self):",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"2022 NVIDIA Corporation. All rights reserved. # # Licensed under the Apache License,",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase):",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol =",
"'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {\"activation\":",
"TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"- 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 }",
"act == 'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest):",
"inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not",
"{ 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs =",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX(",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'],",
"self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) -",
")).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') }",
"np.dot(X, Y) + bias if act == 'relu': return relu(out) elif act ==",
"'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype)",
"core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y':",
"self.attrs = {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4,",
"4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5",
"self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\")",
"import paddle.fluid.core as core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16):",
"4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out':",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5,",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def",
"self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y':",
"-1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {'trans_x': True, \"activation\":",
"core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5 *",
"TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"'relu').reshape((2, 2, 8, 128)) } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self):",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5,",
"init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16):",
"} self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128))",
"0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs =",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single",
"def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(),",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True,",
"TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"{\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if",
"class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"- 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1,",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype)",
"self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) -",
"self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self):",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'],",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"x * ( 1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 *",
"'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16):",
"@skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol =",
"= core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128,",
"self.attrs = {\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') }",
"{ 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, 'trans_y': True,",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self):",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol",
"2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) -",
"required by applicable law or agreed to in writing, software # distributed under",
"def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(),",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16):",
"= np.dot(X, Y) + bias if act == 'relu': return relu(out) elif act",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16):",
"self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol",
"applicable law or agreed to in writing, software # distributed under the License",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def",
"'gelu') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if",
"def gelu(x): y_ref = 0.5 * x * ( 1.0 + np.tanh(np.sqrt(2 /",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype",
"{ 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, \"activation\": 'relu'}",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX(",
"= { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True, \"activation\":",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol =",
"or agreed to in writing, software # distributed under the License is distributed",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"* np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask = x > 0 return",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype =",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol =",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single",
"} self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x':",
"skip_check_inplace_ci def gelu(x): y_ref = 0.5 * x * ( 1.0 + np.tanh(np.sqrt(2",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"np import paddle import paddle.fluid.core as core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci",
"All rights reserved. # # Licensed under the Apache License, Version 2.0 (the",
"self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self):",
"compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs =",
"self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) }",
"= { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias':",
"TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol =",
"{ 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype = np.float16 self.atol",
"class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu')",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T,",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol =",
"governing permissions and # limitations under the License. from __future__ import print_function import",
"0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8,",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self):",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"= { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) -",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"{ 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128,",
"self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) -",
"NVIDIA Corporation. All rights reserved. # # Licensed under the Apache License, Version",
"License. # You may obtain a copy of the License at # #",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self):",
"0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs =",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self):",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self):",
"\"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5,",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def",
"- 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2,",
"8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype =",
"\"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype)",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def",
"compliance with the License. # You may obtain a copy of the License",
"{'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def",
"= { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs",
"= { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) -",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self):",
"TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs = {",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype =",
"def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X':",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype",
"class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True, \"activation\": 'relu'} def",
"TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype",
"under the License. from __future__ import print_function import unittest import numpy as np",
"= 0.5 * x * ( 1.0 + np.tanh(np.sqrt(2 / np.pi) * (x",
"class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 if __name__ ==",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX):",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol =",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype =",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol =",
"> 0 return x * mask def get_output(X, Y, bias, act): out =",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)),",
"= core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128,",
"self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) -",
"return relu(out) elif act == 'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"{ 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128,",
"= { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'} def",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def",
"= core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4,",
"self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True,",
"return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap",
"TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
")).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') }",
"self.inputs = { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype)",
"not use this file except in compliance with the License. # You may",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype =",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3",
"= {\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T,",
"} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype",
"{\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self):",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"as core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double",
"relu(x): mask = x > 0 return x * mask def get_output(X, Y,",
"{ 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5,",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def",
"import numpy as np import paddle import paddle.fluid.core as core from op_test import",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'],",
"'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, \"activation\": 'relu'} def",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'],",
"compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self):",
"class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5 * x * ( 1.0",
"np.pi) * (x + 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask",
"get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype =",
"# you may not use this file except in compliance with the License.",
"'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs =",
"agreed to in writing, software # distributed under the License is distributed on",
"TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"3)))) return y_ref.astype(x.dtype) def relu(x): mask = x > 0 return x *",
"(the \"License\"); # you may not use this file except in compliance with",
"Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0",
"mask = x > 0 return x * mask def get_output(X, Y, bias,",
"- 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'],",
"y_ref = 0.5 * x * ( 1.0 + np.tanh(np.sqrt(2 / np.pi) *",
"self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y':",
"test_check_output(self): if self.dtype == np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no",
"- 0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'],",
"import unittest import numpy as np import paddle import paddle.fluid.core as core from",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype =",
"{ 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype = np.float16 self.atol",
"# Unless required by applicable law or agreed to in writing, software #",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T,",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype =",
"by applicable law or agreed to in writing, software # distributed under the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype",
"np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask = x > 0 return x",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self):",
"np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) -",
"'relu') } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16",
"'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype =",
"2, 8, 128)) } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self):",
"self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled",
"= \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) -",
"= { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs",
"0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs =",
"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"limitations under the License. from __future__ import print_function import unittest import numpy as",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'],",
"file except in compliance with the License. # You may obtain a copy",
"self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype)",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype =",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'],",
"class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def",
"def get_output(X, Y, bias, act): out = np.dot(X, Y) + bias if act",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def",
"{ 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5,",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"License for the specific language governing permissions and # limitations under the License.",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"- 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs",
"self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4,",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"to in writing, software # distributed under the License is distributed on an",
"class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs =",
"{'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16):",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol =",
"paddle import paddle.fluid.core as core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x):",
"implied. # See the License for the specific language governing permissions and #",
"- 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2,",
"\"License\"); # you may not use this file except in compliance with the",
"* (x + 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask =",
"x * mask def get_output(X, Y, bias, act): out = np.dot(X, Y) +",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"= { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias':",
"op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled",
"} self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x':",
"(c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation.",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype",
"'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol =",
"TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self):",
"= core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5,",
"= {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3",
"4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5",
"core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype)",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"or implied. # See the License for the specific language governing permissions and",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2,",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"= { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype = np.float16",
"# Copyright (c) 2022 NVIDIA Corporation. All rights reserved. # # Licensed under",
"self.dtype == np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\")",
"np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled",
"self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'}",
"* mask def get_output(X, Y, bias, act): out = np.dot(X, Y) + bias",
"- 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T,",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"= \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2, 8,",
"Reserved. # Copyright (c) 2022 NVIDIA Corporation. All rights reserved. # # Licensed",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type =",
"TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 if __name__ == \"__main__\":",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"* x * ( 1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715",
"in writing, software # distributed under the License is distributed on an \"AS",
"} self.attrs = {'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype =",
"with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 if",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype",
"'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype",
"= {'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu')",
"compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5 * x *",
"TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"self.attrs = {\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') }",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def",
")).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') }",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def",
"0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs =",
"Copyright (c) 2022 NVIDIA Corporation. All rights reserved. # # Licensed under the",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"bias, act): out = np.dot(X, Y) + bias if act == 'relu': return",
"np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\":",
"- 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"128)) } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16",
"and # limitations under the License. from __future__ import print_function import unittest import",
"self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def",
"return y_ref.astype(x.dtype) def relu(x): mask = x > 0 return x * mask",
"0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs",
"TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"0 return x * mask def get_output(X, Y, bias, act): out = np.dot(X,",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16):",
"All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. All rights reserved. #",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase):",
"you may not use this file except in compliance with the License. #",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def",
"with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"{\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self):",
"'relu').reshape((2, 2, 8, 128)) } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype =",
"{ 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs =",
"compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'],",
"from __future__ import print_function import unittest import numpy as np import paddle import",
"( 1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))",
"'relu') } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase):",
"} self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128))",
"self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2,",
"= core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5,",
"return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(),",
"= { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias':",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self):",
"class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"= core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4,",
"TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\")",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol =",
"init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype == np.float16",
"use this file except in compliance with the License. # You may obtain",
"CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"= x > 0 return x * mask def get_output(X, Y, bias, act):",
"} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\":",
"} self.attrs = {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type",
"np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = {",
"unittest import numpy as np import paddle import paddle.fluid.core as core from op_test",
"2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. All",
")).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'],",
"= { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype = np.float16",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16):",
"'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype)",
"class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"'X': np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias':",
"import paddle import paddle.fluid.core as core from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self):",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type =",
"{'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self):",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu')",
"core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype)",
"= np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype == np.float16 and not",
"TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"np.random.random((2, 2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128,",
"get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self):",
"np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) -",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"= { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, \"activation\":",
"if self.dtype == np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap",
"TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype)",
"Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA",
"0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8,",
"x > 0 return x * mask def get_output(X, Y, bias, act): out",
"- 0.5 } self.attrs = {\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'],",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol =",
"True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self):",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs = { 'Out':",
"self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is",
"== 'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass",
"== 'relu': return relu(out) elif act == 'gelu': return gelu(out) else: return out",
"else: return out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"'relu': return relu(out) elif act == 'gelu': return gelu(out) else: return out @skip_check_inplace_ci(reason=\"no",
"np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled",
"2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype)",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol",
"# # Unless required by applicable law or agreed to in writing, software",
"self.dtype = np.double self.atol = 1e-6 if __name__ == \"__main__\": paddle.enable_static() np.random.seed(0) unittest.main()",
"TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"express or implied. # See the License for the specific language governing permissions",
"def relu(x): mask = x > 0 return x * mask def get_output(X,",
"= np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not",
"compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with",
"128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'gelu'}",
"self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) -",
"'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"\"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5,",
"'relu') } self.attrs = {'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype",
"} self.attrs = {\"activation\": 'gelu'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu')",
"'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype",
"either express or implied. # See the License for the specific language governing",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype",
"class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"= {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self):",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX(",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX(",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX):",
"the specific language governing permissions and # limitations under the License. from __future__",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase):",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol",
"PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. All rights",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single",
"act): out = np.dot(X, Y) + bias if act == 'relu': return relu(out)",
"2, 8, 128)) } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type =",
"get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3",
"np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) -",
"+ 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask = x >",
"the License. # You may obtain a copy of the License at #",
"self.inputs = { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype)",
"(c) 2022 NVIDIA Corporation. All rights reserved. # # Licensed under the Apache",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"= np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"# limitations under the License. from __future__ import print_function import unittest import numpy",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol",
"gelu(x): y_ref = 0.5 * x * ( 1.0 + np.tanh(np.sqrt(2 / np.pi)",
"out = np.dot(X, Y) + bias if act == 'relu': return relu(out) elif",
"as np import paddle import paddle.fluid.core as core from op_test import OpTest, skip_check_grad_ci,",
"import print_function import unittest import numpy as np import paddle import paddle.fluid.core as",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type =",
"TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"= \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) -",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128,",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype =",
"8, 128)) } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol",
"class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
")).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2,",
"1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))) return",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self):",
"mask def get_output(X, Y, bias, act): out = np.dot(X, Y) + bias if",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'],",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double",
"with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"with the License. # You may obtain a copy of the License at",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype =",
"class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs =",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype =",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type =",
"0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x): mask = x > 0",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'],",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0)",
"act == 'relu': return relu(out) elif act == 'gelu': return gelu(out) else: return",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol =",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double",
"init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 if __name__ == \"__main__\": paddle.enable_static() np.random.seed(0)",
"= { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias':",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self):",
"Y, bias, act): out = np.dot(X, Y) + bias if act == 'relu':",
"the License. from __future__ import print_function import unittest import numpy as np import",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype",
"rights reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"if act == 'relu': return relu(out) elif act == 'gelu': return gelu(out) else:",
"TestFuseGemmEpilogueOpReluMTMTFP32(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {\"activation\": 'relu'} def",
"+ np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype)",
"import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5 * x * (",
"\"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2, 2, 8, 4)).astype(self.dtype)",
"- 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 }",
"- 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'gelu'} self.outputs",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol",
")).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2,",
"get_output(X, Y, bias, act): out = np.dot(X, Y) + bias if act ==",
"law or agreed to in writing, software # distributed under the License is",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"the License for the specific language governing permissions and # limitations under the",
"0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type =",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((2,",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX):",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype == np.float16 and",
"CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"2, 8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype)",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6",
"class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 if __name__ == \"__main__\": paddle.enable_static()",
"self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16",
"self.attrs = {'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16",
"np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(),",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase):",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol",
"} self.attrs = {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol",
"numpy as np import paddle import paddle.fluid.core as core from op_test import OpTest,",
"class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"{ 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128,",
"TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'none'} self.outputs = {",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.double",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol",
"= {\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type",
")).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'],",
"out @skip_check_inplace_ci(reason=\"no inplace op\") class TestFuseGemmBase(OpTest): pass @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP16(TestFuseGemmBase): def setUp(self): self.op_type",
"CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"- 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4,",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP64(TestFuseGemmEpilogueOpReluMTMTFP16): def init_dtype_type(self):",
"{ 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128,",
"= {'trans_x': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3",
"def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype ==",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP32MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.single self.atol",
"in compliance with the License. # You may obtain a copy of the",
"return x * mask def get_output(X, Y, bias, act): out = np.dot(X, Y)",
"init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, 'trans_y': True, \"activation\":",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"= 1e-3 def test_check_output(self): if self.dtype == np.float16 and not core.is_float16_supported( self.place): return",
"self.inputs = { 'X': np.random.random((8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5,",
"0.5 } self.attrs = {\"activation\": 'none'} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'],",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6",
"Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. All rights reserved.",
"<filename>python/paddle/fluid/tests/unittests/test_fused_gemm_epilogue_op.py # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c)",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"'relu') } self.attrs = {'trans_y': True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16",
"class TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"See the License for the specific language governing permissions and # limitations under",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type =",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4,",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self):",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype =",
"CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16):",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. from __future__ import print_function import unittest import numpy as np import paddle",
"TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) -",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type =",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype)",
"core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y':",
"= 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\")",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase):",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self):",
"not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is",
"bias if act == 'relu': return relu(out) elif act == 'gelu': return gelu(out)",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP64MultiDimX( TestFuseGemmEpilogueOpReluMMFP16MultiDimX):",
"0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'none'} self.outputs =",
"TestFuseGemmEpilogueOpReluMTMFP32(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"- 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'none'} self.outputs",
"'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype = np.float16 self.atol =",
"CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self):",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"self.outputs = { 'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) }",
"TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. All rights reserved. # #",
"* ( 1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x,",
"} self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3",
"TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol =",
"permissions and # limitations under the License. from __future__ import print_function import unittest",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"for the specific language governing permissions and # limitations under the License. from",
"except in compliance with the License. # You may obtain a copy of",
"0.5 * x * ( 1.0 + np.tanh(np.sqrt(2 / np.pi) * (x +",
"self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'gelu') } def init_dtype_type(self): self.dtype =",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self):",
"self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is",
"= { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, 'trans_y':",
"TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"+ bias if act == 'relu': return relu(out) elif act == 'gelu': return",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def",
"class TestFuseGemmEpilogueOpGeluMMFP32(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap op\")",
"CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"__future__ import print_function import unittest import numpy as np import paddle import paddle.fluid.core",
"core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype =",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type",
"- 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'], self.inputs['Bias'], 'relu') } self.attrs",
"128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'none'}",
"with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP32(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"Y) + bias if act == 'relu': return relu(out) elif act == 'gelu':",
"} self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y':",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"'Out': get_output(self.inputs['X'].reshape((4, -1)).T, self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {'trans_x':",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP32(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.single self.atol",
"= \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 2, 2,",
"self.atol = 1e-3 def test_check_output(self): if self.dtype == np.float16 and not core.is_float16_supported( self.place):",
"np.float16 self.atol = 1e-3 def test_check_output(self): if self.dtype == np.float16 and not core.is_float16_supported(",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
"'Y': np.random.random((128, 4)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs =",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMTFP16(TestFuseGemmBase):",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place",
")).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') }",
"0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs",
"get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, 'trans_y': True, \"activation\": 'relu'}",
"not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place =",
"CUDA\") class TestFuseGemmEpilogueOpGeluMMFP64(TestFuseGemmEpilogueOpGeluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64(TestFuseGemmEpilogueOpReluMTMFP16): def init_dtype_type(self): self.dtype = np.double self.atol",
"self.inputs['Bias'], 'relu') } self.attrs = {\"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol",
"8, 4)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) -",
"CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs",
"CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_x': True, 'trans_y': True, \"activation\": 'relu'} def",
"self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'none') } def init_dtype_type(self): self.dtype =",
"is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMTMFP64MultiDimX( TestFuseGemmEpilogueOpReluMTMFP16MultiDimX): def init_dtype_type(self): self.dtype = np.double",
"\"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\"",
"with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP16(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.attrs = {\"activation\": 'none'} self.outputs = { 'Out':",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype = np.single self.atol = 1e-6 @skip_check_grad_ci(reason=\"no",
"== np.float16 and not core.is_float16_supported( self.place): return self.check_output_with_place(self.place, atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not",
"'Bias': np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'].T, self.inputs['Y'].T, self.inputs['Bias'],",
"from op_test import OpTest, skip_check_grad_ci, skip_check_inplace_ci def gelu(x): y_ref = 0.5 * x",
"with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type()",
"op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP64(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self):",
"8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias': np.random.random((128, )).astype(self.dtype) - 0.5",
"'X': np.random.random((4, 2, 2, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype) - 0.5, 'Bias':",
"np.random.random((128, )).astype(self.dtype) - 0.5 } self.outputs = { 'Out': get_output(self.inputs['X'], self.inputs['Y'], self.inputs['Bias'], 'relu')",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMTFP32(TestFuseGemmEpilogueOpReluMMTFP16): def init_dtype_type(self): self.dtype",
"grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpReluMMFP16(TestFuseGemmBase): def",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"/ np.pi) * (x + 0.044715 * np.power(x, 3)))) return y_ref.astype(x.dtype) def relu(x):",
"TestFuseGemmEpilogueOpReluMTMFP16MultiDimX(TestFuseGemmBase): def setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = {",
"@skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpGeluMMFP16(TestFuseGemmBase):",
"{ 'Out': get_output(self.inputs['X'], self.inputs['Y'].T, self.inputs['Bias'], 'relu') } self.attrs = {'trans_y': True, \"activation\": 'relu'}",
"True, \"activation\": 'relu'} def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self):",
"core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((4, 8)).astype(self.dtype) - 0.5, 'Y': np.random.random((4, 128)).astype(self.dtype)",
"CUDA\") class TestFuseGemmEpilogueOpReluMMFP64(TestFuseGemmEpilogueOpReluMMFP16): def init_dtype_type(self): self.dtype = np.double self.atol = 1e-6 @skip_check_grad_ci(reason=\"no grap",
"'none') } def init_dtype_type(self): self.dtype = np.float16 self.atol = 1e-3 def test_check_output(self): if",
"atol=self.atol) @skip_check_grad_ci(reason=\"no grap op\") @unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class",
"@unittest.skipIf(not core.is_compiled_with_cuda(), \"core is not compiled with CUDA\") class TestFuseGemmEpilogueOpNoneMMFP64(TestFuseGemmEpilogueOpNoneMMFP16): def init_dtype_type(self): self.dtype",
"get_output(self.inputs['X'].reshape((-1, 4)), self.inputs['Y'], self.inputs['Bias'], 'relu').reshape((2, 2, 8, 128)) } self.attrs = {\"activation\": 'relu'}",
"setUp(self): self.op_type = \"fused_gemm_epilogue\" self.place = core.CUDAPlace(0) self.init_dtype_type() self.inputs = { 'X': np.random.random((8,"
] |
[
"= FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов jpg и png')]) submit",
"class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture",
"regexp class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()])",
"import re from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from",
"FileAllowed, FileRequired from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp",
"FileRequired from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp class",
"validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы",
"= StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(),",
"import DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст",
"StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название",
"wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text =",
"text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только",
"= TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения",
"from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, TextAreaField, SubmitField from",
"SubmitField from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()])",
"validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов jpg и png')]) submit = SubmitField('Подтвердить')",
"flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators",
"from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import",
"статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов jpg",
"picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов jpg и png')])",
"TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов",
"ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture =",
"validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов jpg и",
"import FileField, FileAllowed, FileRequired from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import",
"FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Допустимы только изображения форматов jpg и png')]) submit =",
"re from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms",
"from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm):",
"статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg', 'png'],",
"wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title",
"title = StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка',",
"flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField,",
"FileField, FileAllowed, FileRequired from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired,",
"import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, TextAreaField,",
"DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи',",
"import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title =",
"StringField('Название статьи', validators=[DataRequired()]) text = TextAreaField('Текст статьи', validators=[DataRequired()]) picture = FileField('Картинка', validators=[FileRequired(), FileAllowed(['jpg',",
"TextAreaField, SubmitField from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название статьи',",
"from wtforms.validators import DataRequired, regexp class ArticleForm(FlaskForm): title = StringField('Название статьи', validators=[DataRequired()]) text",
"FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, TextAreaField, SubmitField"
] |
[
"**kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send",
"\"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s",
"\"\"\" import sys import time import zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream",
"for unknown query: %r', qid) return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg)",
"rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on timeout, needs to",
"around ZMQStream \"\"\" import sys import time import zmq from zmq.eventloop import IOLoop",
"elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self,",
"= None if timeout: deadline = time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout)",
"self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to",
"cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast",
"from cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream'] # # simple wrapper around",
"replies are ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self,",
"must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg:",
"zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop = ioloop or IOLoop.instance()",
"cmsg = CCMessage(zmsg) route = cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply route:",
"import sys import time import zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import",
"zctx = zctx or zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s = zctx.socket",
"self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop",
"ZMQStream. It must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed,",
"callback function based on request id. \"\"\" # create query id prefix qid",
"for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs): self.qid =",
"can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route() if len(route) != 1:",
"# create query id prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq += 1",
"timeout: deadline = time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc):",
"\"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream.",
"\"\"\"Actual callback that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route() if",
"= CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on single stream # class",
"= skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg =",
"def __init__(self, qid, cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg = cmsg self.cbfunc",
"= {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state. Further replies are ignored.\"\"\"",
"qid, timeout=0): if qid in self.query_cache: qi = self.query_cache[qid] qi.send_to(self.ccs) qi.set_timeout(timeout) else: pass",
"super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg))",
"arg): \"\"\"Run callback, re-wire timeout and query if needed.\"\"\" keep, timeout = self.cbfunc(arg)",
"needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def",
"\"\"\"Run callback, re-wire timeout and query if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r',",
"if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout for task,",
"= sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize()",
"timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout):",
"# # simple wrapper around ZMQStream # class CCStream (ZMQStream): \"\"\" Adds CCMessage",
"zmsg_size from cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream'] # # simple wrapper",
"timeout for task, None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None",
"to original request based on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100",
"socket. Add request-id into route, later map replies to original request based on",
"zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route()",
"unlimited memory (send queue) growth. \"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize =",
"launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and query if needed.\"\"\" keep, timeout =",
"callback details for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs):",
"= rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on timeout, needs",
"(send queue) growth. \"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize',",
"= route[0] if qid not in self.query_cache: self.log.error('reply for unknown query: %r', qid)",
"callback that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route() if len(route)",
"in self.query_cache: self.log.error('reply for unknown query: %r', qid) return msg = cmsg.get_payload(self.xtx) qi",
"resend(self, qid, timeout=0): if qid in self.query_cache: qi = self.query_cache[qid] qi.send_to(self.ccs) qi.set_timeout(timeout) else:",
"def set_timeout(self, timeout): \"\"\"Set new timeout for task, None means drop it\"\"\" if",
"ZMQStream # class CCStream (ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream as well",
"callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # #",
"are ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg,",
"kwargs.pop ('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize = 1000 elif self.qmaxsize <=",
"def resend(self, qid, timeout=0): if qid in self.query_cache: qi = self.query_cache[qid] qi.send_to(self.ccs) qi.set_timeout(timeout)",
"ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback",
"stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def",
"skytools from cc.message import CCMessage, zmsg_size from cc.util import stat_inc __all__ = ['CCStream',",
"= zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs =",
"to ZMQStream as well as protection (on by default) against unlimited memory (send",
"= skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500 def __init__(self, cc_url, xtx, ioloop=None,",
"not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r',",
"self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs)",
"timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\" res = [None] def sync_cb(_rep): res[0]",
"cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on single stream # class QueryInfo: \"\"\"Store",
"s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop",
"on timeout, needs to handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout",
"self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg, *args, **kwargs): if",
"= ['CCStream', 'CCReqStream'] # # simple wrapper around ZMQStream # class CCStream (ZMQStream):",
"self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg,",
"= 100 zmq_linger = 500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\"",
"self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout for task, None means",
"__init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize is None:",
"Returns first reply. \"\"\" res = [None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop()",
"self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on timeout,",
"%r', route) return qid = route[0] if qid not in self.query_cache: self.log.error('reply for",
"zmsg): \"\"\"Internal callback on ZMQStream. It must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg)",
"msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to callback function based on request",
"cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg)",
"sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize() <",
"self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm)",
"# # request multiplexer on single stream # class QueryInfo: \"\"\"Store callback details",
"Adds CCMessage methods to ZMQStream as well as protection (on by default) against",
"sys import time import zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream",
"timeout=0): \"\"\"Asynchronous query. Maps replies to callback function based on request id. \"\"\"",
"ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\" res = [None] def",
"state. Further replies are ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None)",
"cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on single stream #",
"send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC socket. Add request-id into",
"self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize = 1000 elif",
"single stream # class QueryInfo: \"\"\"Store callback details for query.\"\"\" log = skytools.getLogger('QueryInfo')",
"self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline = time.time() + timeout self.timeout_ref =",
"self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout",
"self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new",
"self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that can",
"msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\" cmsg",
"\"\"\" # create query id prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq +=",
"100 zmq_linger = 500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx",
"self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline = time.time() + timeout self.timeout_ref",
"= self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout)",
"into route, later map replies to original request based on that. \"\"\" log",
"s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs",
"= [None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb,",
"qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid in self.query_cache: qi",
"qid not in self.query_cache: self.log.error('reply for unknown query: %r', qid) return msg =",
"cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It must not throw exceptions.",
"multiplexer on single stream # class QueryInfo: \"\"\"Store callback details for query.\"\"\" log",
"request-id into route, later map replies to original request based on that. \"\"\"",
"self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC socket.",
"__init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop",
"on_timeout(self): \"\"\"Called by ioloop on timeout, needs to handle exceptions\"\"\" try: self.timeout_ref =",
"try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def handle_recv_real(self, zmsg):",
"= qid self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref = None self.ioloop =",
"('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\"",
"1: self.log.error('Invalid reply route: %r', route) return qid = route[0] if qid not",
"ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0):",
"send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that",
"to handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def",
"send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args,",
"by ioloop on timeout, needs to handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None)",
"qid = \"Q%06d\" % self.query_id_seq self.query_id_seq += 1 # create message, add query",
"def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and query if needed.\"\"\" keep, timeout",
"None) if self.qmaxsize is None: self.qmaxsize = 1000 elif self.qmaxsize <= 0: self.qmaxsize",
"# request multiplexer on single stream # class QueryInfo: \"\"\"Store callback details for",
"\"\"\"Set new timeout for task, None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref",
"stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s =",
"\"\"\"Synchronous query. Returns first reply. \"\"\" res = [None] def sync_cb(_rep): res[0] =",
"None: self.qmaxsize = 1000 elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args,",
"cc.message import CCMessage, zmsg_size from cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream'] #",
"cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called",
"(zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize =",
"self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state.",
"details for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs): self.qid",
"add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self)",
"= \"Q%06d\" % self.query_id_seq self.query_id_seq += 1 # create message, add query id",
"except: self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and query",
"for task, None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if",
"request based on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger =",
"cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid in self.query_cache:",
"on request id. \"\"\" # create query id prefix qid = \"Q%06d\" %",
"CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx self.query_id_seq =",
"self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout for task, None means drop it\"\"\"",
"rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on timeout, needs to handle exceptions\"\"\" try:",
"throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route() if len(route) != 1: self.log.error('Invalid",
"*args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg):",
"stat_inc __all__ = ['CCStream', 'CCReqStream'] # # simple wrapper around ZMQStream # class",
"message, add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc,",
"to callback function based on request id. \"\"\" # create query id prefix",
"def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal",
"= None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire",
"qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx self.query_id_seq = 1 self.query_cache",
"on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500 def",
"query id prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq += 1 # create",
"None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on",
"callback crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and query if needed.\"\"\"",
"!= 1: self.log.error('Invalid reply route: %r', route) return qid = route[0] if qid",
"CCMessage methods to ZMQStream as well as protection (on by default) against unlimited",
"qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first reply.",
"# create message, add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid,",
"qid self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop",
"timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies",
"ZMQStream as well as protection (on by default) against unlimited memory (send queue)",
"by default) against unlimited memory (send queue) growth. \"\"\" def __init__ (self, *args,",
"replies to original request based on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm =",
"API for CC socket. Add request-id into route, later map replies to original",
"1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg)",
"%r', qid) return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid,",
"zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s,",
"return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self,",
"handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route =",
"if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid)",
"queue) growth. \"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None)",
"receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer",
"not in self.query_cache: self.log.error('reply for unknown query: %r', qid) return msg = cmsg.get_payload(self.xtx)",
"self.query_cache: self.log.error('reply for unknown query: %r', qid) return msg = cmsg.get_payload(self.xtx) qi =",
"callback on ZMQStream. It must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception:",
"to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg):",
"Add request-id into route, later map replies to original request based on that.",
"try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run",
"cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi",
"= ioloop self.xtx = xtx self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def",
"query: %r', qid) return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self,",
"self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query.",
"= self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It must not",
"\"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def handle_recv_real(self,",
"self.on_recv(convert_cmsg) # # request multiplexer on single stream # class QueryInfo: \"\"\"Store callback",
"on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg)",
"time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream:",
"*args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc",
"rqs): self.qid = qid self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref = None",
"**kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize = 1000",
"timeout): \"\"\"Set new timeout for task, None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref)",
"unknown query: %r', qid) return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def",
"qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid",
"= self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx self.query_id_seq = 1 self.query_cache =",
"dropping msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\"",
"super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize:",
"None if timeout: deadline = time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def",
"qi = self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous",
"msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid",
"API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It",
"stream # class QueryInfo: \"\"\"Store callback details for query.\"\"\" log = skytools.getLogger('QueryInfo') def",
"s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx",
"# simple wrapper around ZMQStream # class CCStream (ZMQStream): \"\"\" Adds CCMessage methods",
"cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply route: %r', route) return qid =",
"(self, msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs)",
"around ZMQStream # class CCStream (ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream as",
"= QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def",
"cbfunc, rqs): self.qid = qid self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref =",
"zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg)",
"def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to callback function based",
"self.query_id_seq += 1 # create message, add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid])",
"0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous",
"self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual",
"id prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq += 1 # create message,",
"qid) return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0):",
"msg, timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\" res = [None] def sync_cb(_rep):",
"convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on single stream",
"\"\"\" res = [None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False, 0)",
"(zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop,",
"def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance()",
"self.query_id_seq self.query_id_seq += 1 # create message, add query id cmsg = self.xtx.create_cmsg(msg)",
"methods to ZMQStream as well as protection (on by default) against unlimited memory",
"self.qmaxsize is None: self.qmaxsize = 1000 elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize",
"set_timeout(self, timeout): \"\"\"Set new timeout for task, None means drop it\"\"\" if self.timeout_ref:",
"id. \"\"\" # create query id prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq",
"as well as protection (on by default) against unlimited memory (send queue) growth.",
"deadline = time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc)",
"zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm)",
"remove_query(self, qid): \"\"\"Drop query state. Further replies are ignored.\"\"\" qi = self.query_cache.get(qid) if",
"function based on request id. \"\"\" # create query id prefix qid =",
"self.ioloop = ioloop self.xtx = xtx self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv)",
"if timeout: deadline = time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self,",
"self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx",
"ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop = ioloop or",
"(ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream as well as protection (on by",
"sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return",
"based on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500",
"stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to",
"protection (on by default) against unlimited memory (send queue) growth. \"\"\" def __init__",
"cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return",
"against unlimited memory (send queue) growth. \"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize",
"qid, cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg = cmsg self.cbfunc = cbfunc",
"self.qid = qid self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref = None self.ioloop",
"def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback",
"timeout=0): if qid in self.query_cache: qi = self.query_cache[qid] qi.send_to(self.ccs) qi.set_timeout(timeout) else: pass #",
"Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that",
"is None: self.qmaxsize = 1000 elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream,",
"keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout for",
"= xtx self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop",
"default) against unlimited memory (send queue) growth. \"\"\" def __init__ (self, *args, **kwargs):",
"exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self, arg):",
"self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC socket. Add request-id into route, later",
"self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It must not throw",
"if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline = time.time() + timeout",
"cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to callback function based on request id.",
"self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for",
"import stat_inc __all__ = ['CCStream', 'CCReqStream'] # # simple wrapper around ZMQStream #",
"wrapper around ZMQStream # class CCStream (ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream",
"prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq += 1 # create message, add",
"if qid in self.query_cache: qi = self.query_cache[qid] qi.send_to(self.ccs) qi.set_timeout(timeout) else: pass # ?",
"self).__init__(*args, **kwargs) def send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream,",
"zmq_hwm = 100 zmq_linger = 500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize",
"self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by",
"crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and query if needed.\"\"\" keep,",
"that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request",
"class CCStream (ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream as well as protection",
"% self.query_id_seq self.query_id_seq += 1 # create message, add query id cmsg =",
"['CCStream', 'CCReqStream'] # # simple wrapper around ZMQStream # class CCStream (ZMQStream): \"\"\"",
"self.log.error('Invalid reply route: %r', route) return qid = route[0] if qid not in",
"None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout",
"msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else:",
"\"\"\"Store callback details for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc,",
"500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or",
"query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs): self.qid = qid",
"self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc",
"= 1000 elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def",
"throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg)",
"QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self,",
"or zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM,",
"= rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on timeout, needs to handle exceptions\"\"\"",
"route, later map replies to original request based on that. \"\"\" log =",
"= ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER,",
"self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC socket. Add",
"if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first",
"= cmsg self.cbfunc = cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query =",
"query state. Further replies are ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del self.query_cache[qid]",
"len(route) != 1: self.log.error('Invalid reply route: %r', route) return qid = route[0] if",
"CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on single stream # class QueryInfo:",
"CC socket. Add request-id into route, later map replies to original request based",
"self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size",
"CCMessage, zmsg_size from cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream'] # # simple",
"< self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped',",
"self.timeout_ref = None if timeout: deadline = time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline,",
"def handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route",
"1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state. Further replies",
"cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop =",
"create query id prefix qid = \"Q%06d\" % self.query_id_seq self.query_id_seq += 1 #",
"cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It must",
"qid = route[0] if qid not in self.query_cache: self.log.error('reply for unknown query: %r',",
"0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg, *args, **kwargs):",
"ioloop = ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt",
"CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on",
"replies to callback function based on request id. \"\"\" # create query id",
"self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg",
"cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives",
"def remove_query(self, qid): \"\"\"Drop query state. Further replies are ignored.\"\"\" qi = self.query_cache.get(qid)",
"from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message import",
"\"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) #",
"self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state. Further replies are ignored.\"\"\" qi =",
"%r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw exceptions.\"\"\" cmsg =",
"CCReqStream: \"\"\"Request-based API for CC socket. Add request-id into route, later map replies",
"(zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop =",
"zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message import CCMessage,",
"ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx self.query_id_seq = 1",
"based on request id. \"\"\" # create query id prefix qid = \"Q%06d\"",
"res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to callback function",
"if len(route) != 1: self.log.error('Invalid reply route: %r', route) return qid = route[0]",
"self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop on timeout, needs to handle",
"cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream'] # # simple wrapper around ZMQStream",
"sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps",
"(msg, *args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self,",
"ioloop self.xtx = xtx self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self,",
"def send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg,",
"\"\"\"Wrapper around ZMQStream \"\"\" import sys import time import zmq from zmq.eventloop import",
"from cc.message import CCMessage, zmsg_size from cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream']",
"route: %r', route) return qid = route[0] if qid not in self.query_cache: self.log.error('reply",
"query. Maps replies to callback function based on request id. \"\"\" # create",
"(msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set",
"means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline =",
"route = cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply route: %r', route) return",
"def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg = CCMessage(zmsg)",
"Further replies are ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def",
"def __init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize is",
"def on_timeout(self): \"\"\"Called by ioloop on timeout, needs to handle exceptions\"\"\" try: self.timeout_ref",
"_rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self,",
"original request based on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger",
"= cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply route: %r', route) return qid",
"self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg,",
"class CCReqStream: \"\"\"Request-based API for CC socket. Add request-id into route, later map",
"CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def",
"import CCMessage, zmsg_size from cc.util import stat_inc __all__ = ['CCStream', 'CCReqStream'] # #",
"# class QueryInfo: \"\"\"Store callback details for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self,",
"*args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize =",
"zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message import CCMessage, zmsg_size from cc.util import",
"drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline = time.time()",
"= cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self):",
"= zctx or zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ)",
"1 # create message, add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi =",
"zctx or zmq.Context.instance() ioloop = ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt",
"= self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid in self.query_cache: qi =",
"as protection (on by default) against unlimited memory (send queue) growth. \"\"\" def",
"(cc_url) self.ccs = CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx =",
"('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize = 1000 elif self.qmaxsize <= 0:",
"except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback",
"res = [None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg,",
"route) return qid = route[0] if qid not in self.query_cache: self.log.error('reply for unknown",
"= self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set",
"CCStream (ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream as well as protection (on",
"qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\" res =",
"task, None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout:",
"else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage",
"self.xtx = xtx self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid):",
"self.qmaxsize = 1000 elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs)",
"qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs)",
"\"\"\" Adds CCMessage methods to ZMQStream as well as protection (on by default)",
"= CCMessage(zmsg) route = cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply route: %r',",
"self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg =",
"cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC socket. Add request-id into route,",
"qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid in self.query_cache: qi = self.query_cache[qid] qi.send_to(self.ccs)",
"and query if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout)",
"\"\"\"Asynchronous query. Maps replies to callback function based on request id. \"\"\" #",
"return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if",
"id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid] =",
"if qid not in self.query_cache: self.log.error('reply for unknown query: %r', qid) return msg",
"self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx self.query_id_seq = 1 self.query_cache = {}",
"msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg): \"\"\"Internal callback on",
"(False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc, timeout=0):",
"qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg)",
"(on by default) against unlimited memory (send queue) growth. \"\"\" def __init__ (self,",
"import ZMQStream import skytools from cc.message import CCMessage, zmsg_size from cc.util import stat_inc",
"'CCReqStream'] # # simple wrapper around ZMQStream # class CCStream (ZMQStream): \"\"\" Adds",
"QueryInfo: \"\"\"Store callback details for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg,",
"timeout and query if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep:",
"return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def ccquery_async(self, msg, cbfunc,",
"query if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else:",
"handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It must not throw exceptions. \"\"\" try:",
"for CC socket. Add request-id into route, later map replies to original request",
"growth. \"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if",
"query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg, cbfunc, self) self.query_cache[qid]",
"return res[0] def ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to callback",
"re-wire timeout and query if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if",
"simple wrapper around ZMQStream # class CCStream (ZMQStream): \"\"\" Adds CCMessage methods to",
"new timeout for task, None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref =",
"None means drop it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline",
"= qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg =",
"time import zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools",
"def convert_cmsg(zmsg): cmsg = CCMessage(zmsg) cbfunc(cmsg) self.on_recv(convert_cmsg) # # request multiplexer on single",
"self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and query if",
"zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message",
"from zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message import CCMessage, zmsg_size from cc.util",
"on single stream # class QueryInfo: \"\"\"Store callback details for query.\"\"\" log =",
"def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\" res = [None]",
"import time import zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream import",
"return qid = route[0] if qid not in self.query_cache: self.log.error('reply for unknown query:",
"self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid in self.query_cache: qi = self.query_cache[qid]",
"self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query",
"self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run callback, re-wire timeout and",
"= CCStream(s, ioloop, qmaxsize = self.zmq_hwm) self.ioloop = ioloop self.xtx = xtx self.query_id_seq",
"ZMQStream \"\"\" import sys import time import zmq from zmq.eventloop import IOLoop from",
"if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped', 1)",
"cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg = cmsg self.cbfunc = cbfunc self.timeout_ref",
"qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def",
"ZMQStream import skytools from cc.message import CCMessage, zmsg_size from cc.util import stat_inc __all__",
"request multiplexer on single stream # class QueryInfo: \"\"\"Store callback details for query.\"\"\"",
"def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC socket. Add request-id",
"self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\" res",
"\"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\"",
"= kwargs.pop ('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize = 1000 elif self.qmaxsize",
"del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns first reply. \"\"\"",
"\"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500 def __init__(self, cc_url,",
"[None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout)",
"request id. \"\"\" # create query id prefix qid = \"Q%06d\" % self.query_id_seq",
"xtx self.query_id_seq = 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query",
"cmsg self.cbfunc = cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query",
"def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start()",
"self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query. Returns",
"IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message import CCMessage, zmsg_size from",
"\"\"\"Internal callback on ZMQStream. It must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except",
"It must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping",
"exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply",
"**kwargs) def send_multipart (self, msg, *args, **kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart",
"\"\"\"Called by ioloop on timeout, needs to handle exceptions\"\"\" try: self.timeout_ref = None",
"handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self,",
"import skytools from cc.message import CCMessage, zmsg_size from cc.util import stat_inc __all__ =",
"later map replies to original request based on that. \"\"\" log = skytools.getLogger('CCReqStream')",
"class QueryInfo: \"\"\"Store callback details for query.\"\"\" log = skytools.getLogger('QueryInfo') def __init__(self, qid,",
"else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout for task, None means drop",
"CCMessage(zmsg) route = cmsg.get_route() if len(route) != 1: self.log.error('Invalid reply route: %r', route)",
"{} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state. Further replies are ignored.\"\"\" qi",
"= 500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx",
"keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep) if keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self,",
"reply route: %r', route) return qid = route[0] if qid not in self.query_cache:",
"= _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0] def",
"zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc):",
"s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url) self.ccs = CCStream(s, ioloop, qmaxsize",
"socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self, cbfunc): \"\"\"Set callback that receives CCMessage.\"\"\" def convert_cmsg(zmsg): cmsg",
"(self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize is None: self.qmaxsize",
"qid): \"\"\"Drop query state. Further replies are ignored.\"\"\" qi = self.query_cache.get(qid) if qi:",
"query. Returns first reply. \"\"\" res = [None] def sync_cb(_rep): res[0] = _rep",
"ioloop on timeout, needs to handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except:",
"= self.query_cache.get(qid) if qi: del self.query_cache[qid] qi.set_timeout(None) def ccquery_sync(self, msg, timeout=0): \"\"\"Synchronous query.",
"zmq_linger = 500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx =",
"Maps replies to callback function based on request id. \"\"\" # create query",
"crashed, dropping msg: %r', zmsg) def handle_recv_real(self, zmsg): \"\"\"Actual callback that can throw",
"map replies to original request based on that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm",
"ccquery_async(self, msg, cbfunc, timeout=0): \"\"\"Asynchronous query. Maps replies to callback function based on",
"ioloop or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger)",
"memory (send queue) growth. \"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop",
"route[0] if qid not in self.query_cache: self.log.error('reply for unknown query: %r', qid) return",
"+ timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based",
"self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback crashed') def launch_cb(self, arg): \"\"\"Run callback,",
"callback, re-wire timeout and query if needed.\"\"\" keep, timeout = self.cbfunc(arg) self.log.trace('keep=%r', keep)",
"skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500 def __init__(self, cc_url, xtx, ioloop=None, zctx=None):",
"1000 elif self.qmaxsize <= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart",
"= None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def on_timeout(self): \"\"\"Called by ioloop",
"on ZMQStream. It must not throw exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real",
"import zmq from zmq.eventloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools from",
"def handle_recv(self, zmsg): \"\"\"Internal callback on ZMQStream. It must not throw exceptions. \"\"\"",
"res[0] = _rep self.ioloop.stop() return (False, 0) self.ccquery_async(msg, sync_cb, timeout) self.ioloop.start() return res[0]",
"timeout, needs to handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback",
"self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\"",
"qid def ccpublish(self, msg): \"\"\"Broadcast API.\"\"\" cmsg = self.xtx.create_cmsg(msg) cmsg.send_to(self.ccs) def handle_recv(self, zmsg):",
"= self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API for CC",
"xtx, ioloop=None, zctx=None): \"\"\"Initialize stream.\"\"\" zctx = zctx or zmq.Context.instance() ioloop = ioloop",
"\"Q%06d\" % self.query_id_seq self.query_id_seq += 1 # create message, add query id cmsg",
"\"\"\"Request-based API for CC socket. Add request-id into route, later map replies to",
"log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500 def __init__(self, cc_url, xtx,",
"self.log.error('reply for unknown query: %r', qid) return msg = cmsg.get_payload(self.xtx) qi = self.query_cache[qid]",
"import IOLoop from zmq.eventloop.zmqstream import ZMQStream import skytools from cc.message import CCMessage, zmsg_size",
"first reply. \"\"\" res = [None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return",
"or IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect",
"self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped', 1) stat_inc ('bytes.dropped', zmsg_size (msg)) def",
"__init__(self, qid, cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg = cmsg self.cbfunc =",
"create message, add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi = QueryInfo(qid, cmsg,",
"it\"\"\" if self.timeout_ref: self.ioloop.remove_timeout(self.timeout_ref) self.timeout_ref = None if timeout: deadline = time.time() +",
"\"\"\" def __init__ (self, *args, **kwargs): self.qmaxsize = kwargs.pop ('qmaxsize', None) if self.qmaxsize",
"self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state. Further replies are",
"that. \"\"\" log = skytools.getLogger('CCReqStream') zmq_hwm = 100 zmq_linger = 500 def __init__(self,",
"<= 0: self.qmaxsize = sys.maxsize super(CCStream, self).__init__(*args, **kwargs) def send_multipart (self, msg, *args,",
"log = skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg",
"skytools.getLogger('QueryInfo') def __init__(self, qid, cmsg, cbfunc, rqs): self.qid = qid self.orig_cmsg = cmsg",
"timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class CCReqStream: \"\"\"Request-based API",
"reply. \"\"\" res = [None] def sync_cb(_rep): res[0] = _rep self.ioloop.stop() return (False,",
"IOLoop.instance() s = zctx.socket (zmq.XREQ) s.setsockopt (zmq.HWM, self.zmq_hwm) s.setsockopt (zmq.LINGER, self.zmq_linger) s.connect (cc_url)",
"('bytes.dropped', zmsg_size (msg)) def send_cmsg(self, cmsg): \"\"\"Send CCMessage to socket\"\"\" self.send_multipart(cmsg.zmsg) def on_recv_cmsg(self,",
"needs to handle exceptions\"\"\" try: self.timeout_ref = None self.launch_cb(None) except: self.log.exception('timeout callback crashed')",
"\"\"\"Drop query state. Further replies are ignored.\"\"\" qi = self.query_cache.get(qid) if qi: del",
"that can throw exceptions.\"\"\" cmsg = CCMessage(zmsg) route = cmsg.get_route() if len(route) !=",
"exceptions. \"\"\" try: self.handle_recv_real(zmsg) except Exception: self.log.exception('handle_recv_real crashed, dropping msg: %r', zmsg) def",
"__all__ = ['CCStream', 'CCReqStream'] # # simple wrapper around ZMQStream # class CCStream",
"**kwargs): if self._send_queue.qsize() < self.qmaxsize: super(CCStream, self).send_multipart (msg, *args, **kwargs) else: stat_inc ('count.dropped',",
"cmsg, cbfunc, self) self.query_cache[qid] = qi qi.set_timeout(timeout) qi.send_to(self.ccs) return qid def ccpublish(self, msg):",
"# class CCStream (ZMQStream): \"\"\" Adds CCMessage methods to ZMQStream as well as",
"+= 1 # create message, add query id cmsg = self.xtx.create_cmsg(msg) cmsg.set_route([qid]) qi",
"= cmsg.get_payload(self.xtx) qi = self.query_cache[qid] qi.launch_cb(msg) def resend(self, qid, timeout=0): if qid in",
"= time.time() + timeout self.timeout_ref = self.ioloop.add_timeout(deadline, self.on_timeout) def send_to(self, cc): self.orig_cmsg.send_to(cc) class",
"= 1 self.query_cache = {} self.ccs.on_recv(self.handle_recv) def remove_query(self, qid): \"\"\"Drop query state. Further",
"keep: self.set_timeout(timeout) else: self.remove_query(self.qid) def set_timeout(self, timeout): \"\"\"Set new timeout for task, None",
"self.cbfunc = cbfunc self.timeout_ref = None self.ioloop = rqs.ioloop self.remove_query = rqs.remove_query def",
"if self.qmaxsize is None: self.qmaxsize = 1000 elif self.qmaxsize <= 0: self.qmaxsize =",
"well as protection (on by default) against unlimited memory (send queue) growth. \"\"\""
] |
[
"f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write('",
"descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write('",
"altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n')",
"f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton:",
"altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap:",
"1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n')",
"f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write('",
"f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n')",
"negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity:",
"m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values, required by the",
"axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write('",
"= pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx,",
"name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx,",
"f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write('",
"1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName:",
"2\\n') f.write(' m_Axes:\\n') # Default values, required by the UI f.write(' - serializedVersion:",
"0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n')",
"m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n')",
"\\n') f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write('",
"down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n')",
"f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button",
"positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n')",
"joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName:",
"Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton:",
"button {}'.format(button)) joystick_count = 9 joystick_axis_count = 10 joystick_button_count = 20 with open(fp,",
"m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n')",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName:",
"0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n')",
"f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write('",
"descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write('",
"m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write('",
"altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap:",
"Default values, required by the UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n')",
"serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n')",
"snap: 1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum:",
"f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write('",
"f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write('",
"= 20 with open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('---",
"3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write('",
"UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write('",
"f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write('",
"'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write('",
"{} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n')",
"joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx,",
"f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write('",
"altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n')",
"f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write('",
"f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write('",
"serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n')",
"joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count",
"0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name:",
"invert: 1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' -",
"= 10 joystick_button_count = 20 with open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG",
"f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write('",
"f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write('",
"joyNum: 0\\n') for joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis)",
"range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for joy_bt in range(joystick_button_count): output_button(f,",
"invert: 0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' -",
"gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton:",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write('",
"for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for joy_bt in range(joystick_button_count): output_button(f, joy_idx,",
"3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write('",
"f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values, required by the UI f.write('",
"f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write('",
"altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n')",
"input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n')",
"joystick_count = 9 joystick_axis_count = 10 joystick_button_count = 20 with open(fp, 'wt') as",
"f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name = 'axis",
"output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick",
"type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name",
"m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write('",
"f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write('",
"name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write('",
"descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n')",
"joystick_axis_count = 10 joystick_button_count = 20 with open(fp, 'wt') as f: f.write('%YAML 1.1\\n')",
"values, required by the UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write('",
"type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write('",
"f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write('",
"descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton:",
"= os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' -",
"joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for joy_bt in range(joystick_button_count): output_button(f, joy_idx, joy_bt)",
"3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity:",
"'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n')",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName:",
"invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx",
"0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n')",
"f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n')",
"joystick button 0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write('",
"0\\n') for joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for",
"d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n')",
"'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count =",
"f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity:",
"\\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n')",
"f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton:",
"axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name,",
"sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write(' axis:",
"button 1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap:",
"joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n')",
"f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') #",
"gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert:",
"enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n') f.write('",
"f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName:",
"import os.path cwd = pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset')",
"Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton:",
"0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write('",
"positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead:",
"f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values, required",
"sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis:",
"'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write('",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable",
"positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n')",
"f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity:",
"f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write('",
"required by the UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName:",
"f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n')",
"f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"- serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n')",
"sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write(' axis:",
"f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis):",
"- serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n')",
"{}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2,",
"f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton:",
"UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton:",
"os.path cwd = pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def",
"f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity:",
"f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count):",
"f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write('",
"negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n')",
"m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write('",
"descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write('",
"3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n')",
"UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write('",
"dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write(' type:",
"descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write('",
"axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write('",
"descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton:",
"serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n')",
"s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n')",
"Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton:",
"cwd = pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f,",
"invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f,",
"snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum:",
"UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n')",
"- serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad",
"positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead:",
"1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx))",
"0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n')",
"1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n')",
"f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write('",
"20 with open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13",
"serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values, required by the UI f.write(' -",
"button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count = 10 joystick_button_count = 20 with",
"0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write('",
"!u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default",
"0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName:",
"UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton:",
"f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write('",
"descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton:",
"{}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n')",
"f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write('",
"f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n')",
"f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI",
"joy_idx, name, button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count = 10 joystick_button_count =",
"joy_axis=joy_axis) def output_button(f, joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick",
"\\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n')",
"f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx,",
"0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n')",
"output_button(f, joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button))",
"# Default values, required by the UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name:",
"\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n')",
"= os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0,",
"f.write(' m_Axes:\\n') # Default values, required by the UI f.write(' - serializedVersion: 3\\n')",
"Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton:",
"joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick {}",
"1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion:",
"f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for",
"\\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n')",
"positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead:",
"altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n')",
"descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton:",
"= 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name",
"joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n')",
"f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write('",
"9 joystick_axis_count = 10 joystick_button_count = 20 with open(fp, 'wt') as f: f.write('%YAML",
"f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity:",
"0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx in",
"- serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName:",
"\\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n')",
"f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write('",
"axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write('",
"\\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n')",
"snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum:",
"f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity",
"f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n') f.write(' dead:",
"joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal",
"serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"\\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n')",
"f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write('",
"f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write('",
"positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead:",
"f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI",
"altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap:",
"axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis)",
"10 joystick_button_count = 20 with open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u!",
"f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx,",
"- serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n')",
"f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write('",
"\\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n') f.write('",
"1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n')",
"0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx,",
"f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity",
"{}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name =",
"altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity:",
"os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0):",
"serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"by the UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI",
"UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n')",
"f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n')",
"name, button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count = 10 joystick_button_count = 20",
"UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write('",
"f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write('",
"descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button))",
"button 0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap:",
"\\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n') f.write('",
"name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button):",
"m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n')",
"joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n')",
"escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n') f.write('",
"f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n')",
"joystick {} {}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"(gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n')",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName:",
"descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n')",
"f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count): for joy_axis in",
"f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def",
"Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n')",
"type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write('",
"Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton:",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write('",
"'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name =",
"f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write('",
"negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity:",
"Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton:",
"snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum:",
"\\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick",
"f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write('",
"joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f,",
"f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n')",
"negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity:",
"w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n')",
"up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n')",
"joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical",
"f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button",
"f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write('",
"open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n')",
"serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n')",
"\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n')",
"= 9 joystick_axis_count = 10 joystick_button_count = 20 with open(fp, 'wt') as f:",
"f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write('",
"m_Axes:\\n') # Default values, required by the UI f.write(' - serializedVersion: 3\\n') f.write('",
"0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name:",
"tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n')",
"f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write('",
"- serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n')",
"invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' -",
"as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags:",
"invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' -",
"cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='',",
"\\n') f.write(' altPositiveButton: joystick button 0\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write('",
"f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write('",
"button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name))",
"output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count = 10 joystick_button_count",
"type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write('",
"dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type:",
"name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx,",
"3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write('",
"Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton:",
"3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n')",
"f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n')",
"0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values, required by the UI",
"{}\\n'.format(joy_axis)) f.write(' joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f,",
"3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n')",
"0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type))",
"0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion:",
"{}'.format(button)) joystick_count = 9 joystick_axis_count = 10 joystick_button_count = 20 with open(fp, 'wt')",
"pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name,",
"- serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName:",
"f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write('",
"3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: {}\\n'.format(axis_type)) f.write(' axis: {}\\n'.format(joy_axis))",
"joystick_button_count = 20 with open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n')",
"left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n')",
"1\\n') f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f,",
"f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write('",
"joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for joy_bt in",
"os.path.join(cwd, 'ProjectSettings', 'InputManager.asset') def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion:",
"descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: \\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton:",
"altNegativeButton: \\n') f.write(' altPositiveButton: \\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity:",
"1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName:",
"negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 0\\n')",
"0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName:",
"the UI f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n')",
"axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count):",
"1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion:",
"0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion:",
"altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity:",
"f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write('",
"type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count): for",
"a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n')",
"pathlib import os.path cwd = pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd, 'ProjectSettings',",
"3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton:",
"0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n')",
"f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n') f.write(' descriptiveName: UI Horizontal\\n') f.write(' descriptiveNegativeName:",
"f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write('",
"output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def",
"3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n')",
"with open(fp, 'wt') as f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n')",
"f.write(' type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n')",
"name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count = 9",
"def output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis)",
"2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name:",
"gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert:",
"import pathlib import os.path cwd = pathlib.Path(__file__).parent.absolute() cwd = os.path.abspath(cwd) fp = os.path.join(cwd,",
"f: f.write('%YAML 1.1\\n') f.write('%TAG !u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n')",
"\\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n') f.write(' altPositiveButton: w\\n')",
"0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') for joy_idx in range(joystick_count): for joy_axis",
"3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 1\\n')",
"Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: {}\\n'.format(button)) f.write('",
"def output_unity_axis(f, joy_idx, name, button='', axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name:",
"f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n')",
"f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Vertical\\n')",
"right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton: d\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n')",
"f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick button 1\\n') f.write(' gravity: 3\\n') f.write(' dead:",
"2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name:",
"dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type:",
"3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n')",
"1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n')",
"button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count =",
"f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Horizontal\\n')",
"f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n')",
"def output_button(f, joy_idx, button): name = 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button",
"{}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count = 10",
"0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write('",
"f.write(' altPositiveButton: w\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.001\\n') f.write(' sensitivity: 3\\n') f.write('",
"Horizontal\\n') f.write(' descriptiveName: UI Horizontal (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write('",
"f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write('",
"in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for joy_bt in range(joystick_button_count):",
"0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion:",
"!u! tag:unity3d.com,2011:\\n') f.write('--- !u!13 &1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write('",
"= 'button {}'.format(button) output_unity_axis(f, joy_idx, name, button='joystick button {}'.format(button)) joystick_count = 9 joystick_axis_count",
"snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n') f.write(' joyNum:",
"f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write(' m_Name: Cancel\\n')",
"\\n') f.write(' negativeButton: \\n') f.write(' positiveButton: enter\\n') f.write(' altNegativeButton: \\n') f.write(' altPositiveButton: joystick",
"type: 0\\n') f.write(' axis: 1\\n') f.write(' joyNum: 0\\n') f.write(' - serializedVersion: 3\\n') f.write('",
"0.01\\n') f.write(' sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n')",
"Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write(' positiveButton: up\\n') f.write(' altNegativeButton: s\\n')",
"Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write(' positiveButton: escape\\n') f.write(' altNegativeButton:",
"output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name = 'button {}'.format(button)",
"{}\\n'.format(joy_idx, name)) f.write(' descriptiveName: Reconfigurable gamepad input\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n')",
"Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: \\n') f.write('",
"f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n')",
"f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values, required by",
"for joy_idx in range(joystick_count): for joy_axis in range(joystick_axis_count): output_axis(f, joy_idx, joy_axis) for joy_bt",
"sensitivity: 3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis:",
"{}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f, joy_idx, button): name = 'button",
"joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name, axis_type=2, joy_axis=joy_axis) def output_button(f,",
"serializedVersion: 3\\n') f.write(' m_Name: Submit\\n') f.write(' descriptiveName: Unity UI...\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"&1\\n') f.write('InputManager:\\n') f.write(' m_ObjectHideFlags: 0\\n') f.write(' serializedVersion: 2\\n') f.write(' m_Axes:\\n') # Default values,",
"descriptiveNegativeName: \\n') f.write(' negativeButton: left\\n') f.write(' positiveButton: right\\n') f.write(' altNegativeButton: a\\n') f.write(' altPositiveButton:",
"3\\n') f.write(' m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical (gamepad)\\n') f.write(' descriptiveNegativeName: \\n') f.write('",
"joyNum: {}\\n'.format(joy_idx)) def output_axis(f, joy_idx, joy_axis): name = 'axis {}'.format(joy_axis) output_unity_axis(f, joy_idx, name,",
"joystick button 1\\n') f.write(' gravity: 3\\n') f.write(' dead: 0.01\\n') f.write(' sensitivity: 3\\n') f.write('",
"m_Name: Vertical\\n') f.write(' descriptiveName: UI Vertical\\n') f.write(' descriptiveNegativeName: \\n') f.write(' negativeButton: down\\n') f.write('",
"3\\n') f.write(' snap: 1\\n') f.write(' invert: 1\\n') f.write(' type: 2\\n') f.write(' axis: 1\\n')",
"axis_type=0, joy_axis=0): f.write(' - serializedVersion: 3\\n') f.write(' m_Name: joystick {} {}\\n'.format(joy_idx, name)) f.write('",
"3\\n') f.write(' snap: 1\\n') f.write(' invert: 0\\n') f.write(' type: 2\\n') f.write(' axis: 0\\n')",
"f.write(' invert: 0\\n') f.write(' type: 0\\n') f.write(' axis: 0\\n') f.write(' joyNum: 0\\n') f.write('"
] |
[
"= _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a valid 'tag' consisting of letters,",
"\"Enter a valid 'tag' consisting of letters, numbers, underscores or hyphens.\", \"invalid\", )",
"RegexValidator, _lazy_re_compile slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a valid 'tag'",
"from django.core.validators import RegexValidator, _lazy_re_compile slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter",
"<filename>lego/apps/tags/validators.py from django.core.validators import RegexValidator, _lazy_re_compile slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re,",
"django.core.validators import RegexValidator, _lazy_re_compile slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a",
"validate_tag = RegexValidator( slug_re, \"Enter a valid 'tag' consisting of letters, numbers, underscores",
"slug_re, \"Enter a valid 'tag' consisting of letters, numbers, underscores or hyphens.\", \"invalid\",",
"_lazy_re_compile slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a valid 'tag' consisting",
"slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a valid 'tag' consisting of",
"_lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a valid 'tag' consisting of letters, numbers,",
"= RegexValidator( slug_re, \"Enter a valid 'tag' consisting of letters, numbers, underscores or",
"RegexValidator( slug_re, \"Enter a valid 'tag' consisting of letters, numbers, underscores or hyphens.\",",
"import RegexValidator, _lazy_re_compile slug_re = _lazy_re_compile(r\"^[-a-z0-9æøå_.#%$&/]+\\Z\") validate_tag = RegexValidator( slug_re, \"Enter a valid"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb')",
"spheres in the centroids volume', default=5, type=int) args = parser.parse_args() split_cells(args) if __name__",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"of cells, the other the map of cells def split_cells(args): cells = np.load(args.input)",
"help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with",
"License. # You may obtain a copy of the License at # #",
"python import argparse import sys import itertools import numpy as np sphere_radius =",
"cell_list = cells[0] with open(args.map_output, 'wb') as f: np.save(f, cell_map) # Make volume",
"= list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1",
"cell_map) # Make volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in",
"# limitations under the License. #!/usr/bin/env python import argparse import sys import itertools",
"axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size:",
"import numpy as np sphere_radius = 5 #Take output of cell detect step,",
"open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results splitting",
"splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the",
"into two streams- one list of cells, the other the map of cells",
"compliance with the License. # You may obtain a copy of the License",
"one list of cells, the other the map of cells def split_cells(args): cells",
"in the centroids volume', default=5, type=int) args = parser.parse_args() split_cells(args) if __name__ ==",
"Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the",
"specific language governing permissions and # limitations under the License. #!/usr/bin/env python import",
"limitations under the License. #!/usr/bin/env python import argparse import sys import itertools import",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size",
"Laboratory # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"this file except in compliance with the License. # You may obtain a",
"coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as f:",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"#!/usr/bin/env python import argparse import sys import itertools import numpy as np sphere_radius",
"with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results",
"min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel))",
"you may not use this file except in compliance with the License. #",
"'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def",
"Hopkins University Applied Physics Laboratory # # Licensed under the Apache License, Version",
"Output file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres')",
"for the specific language governing permissions and # limitations under the License. #!/usr/bin/env",
"cells, the other the map of cells def split_cells(args): cells = np.load(args.input) cell_map",
"def split_cells(args): cells = np.load(args.input) cell_map = cells[1] cell_list = cells[0] with open(args.map_output,",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"Copyright 2019 The Johns Hopkins University Applied Physics Laboratory # # Licensed under",
"import argparse import sys import itertools import numpy as np sphere_radius = 5",
"'wb') as f: np.save(f, cell_map) # Make volume out of cell_list cell_centroid_volume =",
"# Make volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list:",
"for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range,",
"ANY KIND, either express or implied. # See the License for the specific",
"split into two streams- one list of cells, the other the map of",
"cell in cell_list: axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size),",
"f: np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _:",
"enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords =",
"parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output",
"of cells def split_cells(args): cells = np.load(args.input) cell_map = cells[1] cell_list = cells[0]",
"= argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file')",
"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",
"pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb')",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"sphere_radius = 5 #Take output of cell detect step, split into two streams-",
"max_range) coords = list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel]",
"use this file except in compliance with the License. # You may obtain",
"main(): parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True,",
"spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres in the centroids volume', default=5, type=int)",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"under the License. #!/usr/bin/env python import argparse import sys import itertools import numpy",
"open(args.map_output, 'wb') as f: np.save(f, cell_map) # Make volume out of cell_list cell_centroid_volume",
"numpy as np sphere_radius = 5 #Take output of cell detect step, split",
"volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list: axes_range =",
"not use this file except in compliance with the License. # You may",
"parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file')",
"help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"the other the map of cells def split_cells(args): cells = np.load(args.input) cell_map =",
"out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list: axes_range = [[],[],[]]",
"= max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for",
"help='Size of the spheres in the centroids volume', default=5, type=int) args = parser.parse_args()",
"cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list: axes_range = [[],[],[]] for i,axes in",
"cell_list: axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range",
"See the License for the specific language governing permissions and # limitations under",
"cell detect step, split into two streams- one list of cells, the other",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False,",
"max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as f: np.save(f,",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"the specific language governing permissions and # limitations under the License. #!/usr/bin/env python",
"University Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"1 with open(args.list_output, 'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f:",
"= min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel in coords: if",
"import itertools import numpy as np sphere_radius = 5 #Take output of cell",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"def main(): parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input',",
"map of cells def split_cells(args): cells = np.load(args.input) cell_map = cells[1] cell_list =",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"with open(args.map_output, 'wb') as f: np.save(f, cell_map) # Make volume out of cell_list",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output file')",
"in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords",
"for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output,",
"as np sphere_radius = 5 #Take output of cell detect step, split into",
"OF ANY KIND, either express or implied. # See the License for the",
"the centroids volume', default=5, type=int) args = parser.parse_args() split_cells(args) if __name__ == '__main__':",
"np sphere_radius = 5 #Take output of cell detect step, split into two",
"required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres in the",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List",
"cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell",
"'--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output",
"# you may not use this file except in compliance with the License.",
"cell_map = cells[1] cell_list = cells[0] with open(args.map_output, 'wb') as f: np.save(f, cell_map)",
"parser.add_argument('--sphere_size', required=False, help='Size of the spheres in the centroids volume', default=5, type=int) args",
"[[],[],[]] for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1)",
"script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output",
"output of cell detect step, split into two streams- one list of cells,",
"agreed to in writing, software # distributed under the License is distributed on",
"f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def main(): parser",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"streams- one list of cells, the other the map of cells def split_cells(args):",
"2019 The Johns Hopkins University Applied Physics Laboratory # # Licensed under the",
"parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres in",
"(the \"License\"); # you may not use this file except in compliance with",
"= cells[0] with open(args.map_output, 'wb') as f: np.save(f, cell_map) # Make volume out",
"= cells[1] cell_list = cells[0] with open(args.map_output, 'wb') as f: np.save(f, cell_map) #",
"list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with",
"of the spheres in the centroids volume', default=5, type=int) args = parser.parse_args() split_cells(args)",
"np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def main(): parser =",
"# # Unless required by applicable law or agreed to in writing, software",
"= np.load(args.input) cell_map = cells[1] cell_list = cells[0] with open(args.map_output, 'wb') as f:",
"# Copyright 2019 The Johns Hopkins University Applied Physics Laboratory # # Licensed",
"express or implied. # See the License for the specific language governing permissions",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"split_cells(args): cells = np.load(args.input) cell_map = cells[1] cell_list = cells[0] with open(args.map_output, 'wb')",
"except in compliance with the License. # You may obtain a copy of",
"volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres in the centroids volume',",
"parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True,",
"by applicable law or agreed to in writing, software # distributed under the",
"of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list: axes_range = [[],[],[]] for",
"governing permissions and # limitations under the License. #!/usr/bin/env python import argparse import",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"'wb') as f: np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results splitting script')",
"np.zeros(cell_map.shape) for cell in cell_list: axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]): min_range",
"either express or implied. # See the License for the specific language governing",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"5 #Take output of cell detect step, split into two streams- one list",
"argparse import sys import itertools import numpy as np sphere_radius = 5 #Take",
"detect step, split into two streams- one list of cells, the other the",
"as f: np.save(f, cell_map) # Make volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape)",
"f: np.save(f, cell_map) # Make volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for",
"args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output,",
"of cell detect step, split into two streams- one list of cells, the",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"required=False, help='Size of the spheres in the centroids volume', default=5, type=int) args =",
"permissions and # limitations under the License. #!/usr/bin/env python import argparse import sys",
"list of cells, the other the map of cells def split_cells(args): cells =",
"file except in compliance with the License. # You may obtain a copy",
"results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True,",
"cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i',",
"in cell_list: axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0)",
"itertools import numpy as np sphere_radius = 5 #Take output of cell detect",
"Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache License,",
"and # limitations under the License. #!/usr/bin/env python import argparse import sys import",
"i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range)",
"cells[0] with open(args.map_output, 'wb') as f: np.save(f, cell_map) # Make volume out of",
"max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel in coords:",
"required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"coords = list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] =",
"parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input",
"with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres in the centroids volume', default=5,",
"License for the specific language governing permissions and # limitations under the License.",
"the spheres in the centroids volume', default=5, type=int) args = parser.parse_args() split_cells(args) if",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"the License. # You may obtain a copy of the License at #",
"to in writing, software # distributed under the License is distributed on an",
"np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as f: np.save(f, cell_list)",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"cells[1] cell_list = cells[0] with open(args.map_output, 'wb') as f: np.save(f, cell_map) # Make",
"with open(args.list_output, 'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f,",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output',",
"implied. # See the License for the specific language governing permissions and #",
"file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres",
"\"License\"); # you may not use this file except in compliance with the",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"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",
"= np.zeros(cell_map.shape) for cell in cell_list: axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]):",
"Make volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list: axes_range",
"applicable law or agreed to in writing, software # distributed under the License",
"cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <=",
"= 5 #Take output of cell detect step, split into two streams- one",
"import sys import itertools import numpy as np sphere_radius = 5 #Take output",
"License. #!/usr/bin/env python import argparse import sys import itertools import numpy as np",
"help='Output volume with spheres') parser.add_argument('--sphere_size', required=False, help='Size of the spheres in the centroids",
"sys import itertools import numpy as np sphere_radius = 5 #Take output of",
"two streams- one list of cells, the other the map of cells def",
"0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range)) for pixel in",
"language governing permissions and # limitations under the License. #!/usr/bin/env python import argparse",
"file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True,",
"centroids volume', default=5, type=int) args = parser.parse_args() split_cells(args) if __name__ == '__main__': main()",
"cells = np.load(args.input) cell_map = cells[1] cell_list = cells[0] with open(args.map_output, 'wb') as",
"min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size), cell_map.shape[i]-1) axes_range[i]=range(min_range, max_range) coords = list(itertools.product(*axes_range))",
"or agreed to in writing, software # distributed under the License is distributed",
"_: parser.print_help()) parser.add_argument('-i', '--input', required=True, help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output',",
"cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell in cell_list: axes_range = [[],[],[]] for i,axes",
"or implied. # See the License for the specific language governing permissions and",
"cells def split_cells(args): cells = np.load(args.input) cell_map = cells[1] cell_list = cells[0] with",
"file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output', required=True, help='Output volume with spheres') parser.add_argument('--sphere_size',",
"the map of cells def split_cells(args): cells = np.load(args.input) cell_map = cells[1] cell_list",
"the License. #!/usr/bin/env python import argparse import sys import itertools import numpy as",
"as f: np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"for cell in cell_list: axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]): min_range =",
"The Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"np.save(f, cell_map) # Make volume out of cell_list cell_centroid_volume = np.zeros(cell_map.shape) for cell",
"as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume) def main():",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"step, split into two streams- one list of cells, the other the map",
"#Take output of cell detect step, split into two streams- one list of",
"np.load(args.input) cell_map = cells[1] cell_list = cells[0] with open(args.map_output, 'wb') as f: np.save(f,",
"other the map of cells def split_cells(args): cells = np.load(args.input) cell_map = cells[1]",
"<= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as f: np.save(f, cell_list) with",
"open(args.list_output, 'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as f: np.save(f, cell_centroid_volume)",
"with the License. # You may obtain a copy of the License at",
"help='Input file') parser.add_argument('--map_output', required=True, help='Map Output file') parser.add_argument('--list_output', required=True, help='List Output file') parser.add_argument('--centroid_volume_output',",
"in coords: if np.linalg.norm(np.array(cell[:3])-np.array(pixel)) <= args.sphere_size: cell_centroid_volume[pixel] = 1 with open(args.list_output, 'wb') as",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"= [[],[],[]] for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range = min(int(axes+args.sphere_size),",
"in writing, software # distributed under the License is distributed on an \"AS",
"axes_range = [[],[],[]] for i,axes in enumerate(cell[:3]): min_range = max(int(axes-args.sphere_size), 0) max_range =",
"= 1 with open(args.list_output, 'wb') as f: np.save(f, cell_list) with open(args.centroid_volume_output, 'wb') as",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"np.save(f, cell_centroid_volume) def main(): parser = argparse.ArgumentParser(description='cell results splitting script') parser.set_defaults(func=lambda _: parser.print_help())"
] |
[
"tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test)",
"actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__ == '__main__': if os.path.exists('model.h5'):",
"pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test) for",
"import os import numpy as np import matplotlib.pyplot as plt class Model(): def",
"x_test self.y_test = y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([",
"Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test)",
"mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train /",
"else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',",
"self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test) for i in range(n):",
"activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self):",
"self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def",
"self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__ == '__main__': if os.path.exists('model.h5'): os.remove('model.h5')",
"self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test",
"for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def",
"= filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test =",
"tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam',",
"= tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0,",
"os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10,",
"import tensorflow as tf import os import numpy as np import matplotlib.pyplot as",
"filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train",
"y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction =",
"epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels])",
"return np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i],",
"def __init__(self, filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) =",
"x_train, x_test = x_train / 255.0, x_test / 255.0 self.x_test = x_test self.y_test",
"as tf import os import numpy as np import matplotlib.pyplot as plt class",
"y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 self.x_test",
"i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self):",
"as plt class Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist",
"metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels):",
"import numpy as np import matplotlib.pyplot as plt class Model(): def __init__(self, filepath='model.h5'):",
"prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test) for i",
"self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])",
"save(self): self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5):",
"\", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__ == '__main__': if",
"255.0, x_test / 255.0 self.x_test = x_test self.y_test = y_test if os.path.exists(filepath): self.model",
"predictions = self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\",",
"mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 self.x_test = x_test",
"28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test,",
"= mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 self.x_test =",
"<gh_stars>0 import tensorflow as tf import os import numpy as np import matplotlib.pyplot",
"= y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)),",
"self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax')",
"plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if",
"/ 255.0 self.x_test = x_test self.y_test = y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath)",
"predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test)",
"tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def",
"np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary')",
"= x_train / 255.0, x_test / 255.0 self.x_test = x_test self.y_test = y_test",
"tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train,",
"as np import matplotlib.pyplot as plt class Model(): def __init__(self, filepath='model.h5'): self.filepath =",
"= x_test self.y_test = y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model =",
"self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction",
"numpy as np import matplotlib.pyplot as plt class Model(): def __init__(self, filepath='model.h5'): self.filepath",
"255.0 self.x_test = x_test self.y_test = y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else:",
"tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10)",
"plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__ == '__main__': if os.path.exists('model.h5'): os.remove('model.h5') Model()",
"__init__(self, filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data()",
"/ 255.0, x_test / 255.0 self.x_test = x_test self.y_test = y_test if os.path.exists(filepath):",
"class Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test,",
"tensorflow as tf import os import numpy as np import matplotlib.pyplot as plt",
"y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0",
"= tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train,",
"= tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ])",
"= self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i])",
"self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels]) return",
"def predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions =",
"n=5): predictions = self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \",",
"x_test / 255.0 self.x_test = x_test self.y_test = y_test if os.path.exists(filepath): self.model =",
"self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def",
"loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self,",
"(x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test /",
"y_test) self.save() def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0])",
"]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save() def save(self): self.model.save(self.filepath)",
"np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__ == '__main__':",
"range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test)",
"self.x_test = x_test self.y_test = y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model",
"x_test = x_train / 255.0, x_test / 255.0 self.x_test = x_test self.y_test =",
"x_train / 255.0, x_test / 255.0 self.x_test = x_test self.y_test = y_test if",
"os import numpy as np import matplotlib.pyplot as plt class Model(): def __init__(self,",
"in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test,",
"np import matplotlib.pyplot as plt class Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath",
"tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test",
"import matplotlib.pyplot as plt class Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath mnist",
"filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train,",
"= self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions = self.model.predict(self.x_test) for i in",
"tf import os import numpy as np import matplotlib.pyplot as plt class Model():",
"matplotlib.pyplot as plt class Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath mnist =",
"print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__ ==",
"activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) self.model.fit(x_train, y_train, epochs=10) self.model.evaluate(x_test, y_test) self.save()",
"def save(self): self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self,",
"self.model.save(self.filepath) def predict(self, pixels): prediction = self.model.predict([pixels]) return np.argmax(prediction[0]) def examples(self, n=5): predictions",
"self.y_test = y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28,",
"self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show()",
"def examples(self, n=5): predictions = self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\",",
"plt class Model(): def __init__(self, filepath='model.h5'): self.filepath = filepath mnist = tf.keras.datasets.mnist (x_train,",
"y_test if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128,",
"if os.path.exists(filepath): self.model = tf.keras.models.load_model(filepath) else: self.model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'),",
"cmap='binary') print(\"Prediction\", np.argmax(predictions[i]), \", actual:\", self.y_test[i]) plt.show() def evaluate(self): self.model.evaluate(self.x_test, self.y_test) if __name__",
"examples(self, n=5): predictions = self.model.predict(self.x_test) for i in range(n): plt.imshow(self.x_test[i], cmap='binary') print(\"Prediction\", np.argmax(predictions[i]),"
] |
[
"un avantage\") print(\"Poids total pour l'équipe 1 : \" + str(poidsE1)) print(\"Poids total",
"(nbMembres * 2) + 1): if i % 2: poidsE1 = poidsE1 +",
"0 poidsE2 = 0 for i in range(1, (nbMembres * 2) + 1):",
"int(input()) else: poidsE2 = poidsE2 + int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1",
"int(input()) poidsE1 = 0 poidsE2 = 0 for i in range(1, (nbMembres *",
"= poidsE1 + int(input()) else: poidsE2 = poidsE2 + int(input()) if poidsE1 >",
"= 0 poidsE2 = 0 for i in range(1, (nbMembres * 2) +",
"* 2) + 1): if i % 2: poidsE1 = poidsE1 + int(input())",
"if i % 2: poidsE1 = poidsE1 + int(input()) else: poidsE2 = poidsE2",
"poidsE2 = poidsE2 + int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1 a un",
"1 a un avantage\") else: print(\"L'équipe 2 a un avantage\") print(\"Poids total pour",
"un avantage\") else: print(\"L'équipe 2 a un avantage\") print(\"Poids total pour l'équipe 1",
"poidsE1 = 0 poidsE2 = 0 for i in range(1, (nbMembres * 2)",
"avantage\") print(\"Poids total pour l'équipe 1 : \" + str(poidsE1)) print(\"Poids total pour",
"> poidsE2: print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe 2 a un avantage\")",
"nbMembres = int(input()) poidsE1 = 0 poidsE2 = 0 for i in range(1,",
"for i in range(1, (nbMembres * 2) + 1): if i % 2:",
"poidsE1 > poidsE2: print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe 2 a un",
"poidsE1 + int(input()) else: poidsE2 = poidsE2 + int(input()) if poidsE1 > poidsE2:",
"= int(input()) poidsE1 = 0 poidsE2 = 0 for i in range(1, (nbMembres",
"avantage\") else: print(\"L'équipe 2 a un avantage\") print(\"Poids total pour l'équipe 1 :",
"total pour l'équipe 1 : \" + str(poidsE1)) print(\"Poids total pour l'équipe 2",
"else: poidsE2 = poidsE2 + int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1 a",
"int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe 2",
"= 0 for i in range(1, (nbMembres * 2) + 1): if i",
"poidsE1 = poidsE1 + int(input()) else: poidsE2 = poidsE2 + int(input()) if poidsE1",
"<gh_stars>1-10 nbMembres = int(input()) poidsE1 = 0 poidsE2 = 0 for i in",
"2: poidsE1 = poidsE1 + int(input()) else: poidsE2 = poidsE2 + int(input()) if",
"poidsE2 = 0 for i in range(1, (nbMembres * 2) + 1): if",
"1): if i % 2: poidsE1 = poidsE1 + int(input()) else: poidsE2 =",
"print(\"Poids total pour l'équipe 1 : \" + str(poidsE1)) print(\"Poids total pour l'équipe",
"+ 1): if i % 2: poidsE1 = poidsE1 + int(input()) else: poidsE2",
"= poidsE2 + int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1 a un avantage\")",
"l'équipe 1 : \" + str(poidsE1)) print(\"Poids total pour l'équipe 2 : \"",
"% 2: poidsE1 = poidsE1 + int(input()) else: poidsE2 = poidsE2 + int(input())",
"+ int(input()) else: poidsE2 = poidsE2 + int(input()) if poidsE1 > poidsE2: print(\"L'équipe",
"2 a un avantage\") print(\"Poids total pour l'équipe 1 : \" + str(poidsE1))",
"range(1, (nbMembres * 2) + 1): if i % 2: poidsE1 = poidsE1",
"+ int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe",
"if poidsE1 > poidsE2: print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe 2 a",
": \" + str(poidsE1)) print(\"Poids total pour l'équipe 2 : \" + str(poidsE2))",
"print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe 2 a un avantage\") print(\"Poids total",
"poidsE2: print(\"L'équipe 1 a un avantage\") else: print(\"L'équipe 2 a un avantage\") print(\"Poids",
"poidsE2 + int(input()) if poidsE1 > poidsE2: print(\"L'équipe 1 a un avantage\") else:",
"pour l'équipe 1 : \" + str(poidsE1)) print(\"Poids total pour l'équipe 2 :",
"0 for i in range(1, (nbMembres * 2) + 1): if i %",
"in range(1, (nbMembres * 2) + 1): if i % 2: poidsE1 =",
"else: print(\"L'équipe 2 a un avantage\") print(\"Poids total pour l'équipe 1 : \"",
"print(\"L'équipe 2 a un avantage\") print(\"Poids total pour l'équipe 1 : \" +",
"1 : \" + str(poidsE1)) print(\"Poids total pour l'équipe 2 : \" +",
"i in range(1, (nbMembres * 2) + 1): if i % 2: poidsE1",
"2) + 1): if i % 2: poidsE1 = poidsE1 + int(input()) else:",
"a un avantage\") print(\"Poids total pour l'équipe 1 : \" + str(poidsE1)) print(\"Poids",
"a un avantage\") else: print(\"L'équipe 2 a un avantage\") print(\"Poids total pour l'équipe",
"i % 2: poidsE1 = poidsE1 + int(input()) else: poidsE2 = poidsE2 +"
] |
[
"= [] def dfs(root, path): if root is None: return path.append(root.val) if root.left",
"= left # self.right = right class Solution: def binaryTreePaths(self, root: TreeNode) ->",
"a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None):",
"def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left",
"self.val = val # self.left = left # self.right = right class Solution:",
"tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val",
"32 ms # @Memory: 15 MB # Definition for a binary tree node.",
"and root.right is None: result.append('->'.join([str(i) for i in path])) dfs(root.left, path) dfs(root.right, path)",
"# self.val = val # self.left = left # self.right = right class",
"= right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result = []",
"for i in path])) dfs(root.left, path) dfs(root.right, path) path.pop() dfs(root, []) return result",
"= val # self.left = left # self.right = right class Solution: def",
"@Runtime: 32 ms # @Memory: 15 MB # Definition for a binary tree",
"2021-02-14 17:30:19 # @Runtime: 32 ms # @Memory: 15 MB # Definition for",
"return path.append(root.val) if root.left is None and root.right is None: result.append('->'.join([str(i) for i",
"# self.right = right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result",
"left=None, right=None): # self.val = val # self.left = left # self.right =",
"root.left is None and root.right is None: result.append('->'.join([str(i) for i in path])) dfs(root.left,",
"is None: result.append('->'.join([str(i) for i in path])) dfs(root.left, path) dfs(root.right, path) path.pop() dfs(root,",
"# class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val",
"if root.left is None and root.right is None: result.append('->'.join([str(i) for i in path]))",
"<filename>Problemset/binary-tree-paths/binary-tree-paths.py<gh_stars>1-10 # @Title: 二叉树的所有路径 (Binary Tree Paths) # @Author: 18015528893 # @Date: 2021-02-14",
"class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result = [] def dfs(root,",
"right=None): # self.val = val # self.left = left # self.right = right",
"@Memory: 15 MB # Definition for a binary tree node. # class TreeNode:",
"val=0, left=None, right=None): # self.val = val # self.left = left # self.right",
"ms # @Memory: 15 MB # Definition for a binary tree node. #",
"# Definition for a binary tree node. # class TreeNode: # def __init__(self,",
"[] def dfs(root, path): if root is None: return path.append(root.val) if root.left is",
"@Title: 二叉树的所有路径 (Binary Tree Paths) # @Author: 18015528893 # @Date: 2021-02-14 17:30:19 #",
"path): if root is None: return path.append(root.val) if root.left is None and root.right",
"Tree Paths) # @Author: 18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime: 32 ms",
"right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result = [] def",
"result.append('->'.join([str(i) for i in path])) dfs(root.left, path) dfs(root.right, path) path.pop() dfs(root, []) return",
"# def __init__(self, val=0, left=None, right=None): # self.val = val # self.left =",
"None and root.right is None: result.append('->'.join([str(i) for i in path])) dfs(root.left, path) dfs(root.right,",
"if root is None: return path.append(root.val) if root.left is None and root.right is",
"# @Author: 18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime: 32 ms # @Memory:",
"# @Date: 2021-02-14 17:30:19 # @Runtime: 32 ms # @Memory: 15 MB #",
"TreeNode) -> List[str]: result = [] def dfs(root, path): if root is None:",
"is None: return path.append(root.val) if root.left is None and root.right is None: result.append('->'.join([str(i)",
"__init__(self, val=0, left=None, right=None): # self.val = val # self.left = left #",
"None: return path.append(root.val) if root.left is None and root.right is None: result.append('->'.join([str(i) for",
"dfs(root, path): if root is None: return path.append(root.val) if root.left is None and",
"root is None: return path.append(root.val) if root.left is None and root.right is None:",
"is None and root.right is None: result.append('->'.join([str(i) for i in path])) dfs(root.left, path)",
"Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result = [] def dfs(root, path):",
"-> List[str]: result = [] def dfs(root, path): if root is None: return",
"# self.left = left # self.right = right class Solution: def binaryTreePaths(self, root:",
"root: TreeNode) -> List[str]: result = [] def dfs(root, path): if root is",
"left # self.right = right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]:",
"path.append(root.val) if root.left is None and root.right is None: result.append('->'.join([str(i) for i in",
"17:30:19 # @Runtime: 32 ms # @Memory: 15 MB # Definition for a",
"self.right = right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result =",
"# @Memory: 15 MB # Definition for a binary tree node. # class",
"def binaryTreePaths(self, root: TreeNode) -> List[str]: result = [] def dfs(root, path): if",
"Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0,",
"List[str]: result = [] def dfs(root, path): if root is None: return path.append(root.val)",
"root.right is None: result.append('->'.join([str(i) for i in path])) dfs(root.left, path) dfs(root.right, path) path.pop()",
"Paths) # @Author: 18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime: 32 ms #",
"15 MB # Definition for a binary tree node. # class TreeNode: #",
"TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left",
"# @Runtime: 32 ms # @Memory: 15 MB # Definition for a binary",
"(Binary Tree Paths) # @Author: 18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime: 32",
"@Date: 2021-02-14 17:30:19 # @Runtime: 32 ms # @Memory: 15 MB # Definition",
"binaryTreePaths(self, root: TreeNode) -> List[str]: result = [] def dfs(root, path): if root",
"@Author: 18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime: 32 ms # @Memory: 15",
"18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime: 32 ms # @Memory: 15 MB",
"result = [] def dfs(root, path): if root is None: return path.append(root.val) if",
"binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): #",
"for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None,",
"class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val #",
"val # self.left = left # self.right = right class Solution: def binaryTreePaths(self,",
"二叉树的所有路径 (Binary Tree Paths) # @Author: 18015528893 # @Date: 2021-02-14 17:30:19 # @Runtime:",
"# @Title: 二叉树的所有路径 (Binary Tree Paths) # @Author: 18015528893 # @Date: 2021-02-14 17:30:19",
"def dfs(root, path): if root is None: return path.append(root.val) if root.left is None",
"MB # Definition for a binary tree node. # class TreeNode: # def",
"node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val =",
"None: result.append('->'.join([str(i) for i in path])) dfs(root.left, path) dfs(root.right, path) path.pop() dfs(root, [])",
"self.left = left # self.right = right class Solution: def binaryTreePaths(self, root: TreeNode)"
] |
[
"Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9,",
"= 0.9, pm = 0.5, max_iter=10, elitism = 0.4, selection = \"tournament\") print(rast_init_pop)",
"0.9, pm = 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop)",
"1], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1,",
"0, 0, 0, 1, 0, 0, 1]]) egg_init_pop = np.array([[1, 0, 1, 0,",
"0.45725239]], pc = 0.9, pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale",
"1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 1, 1,",
"1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1,",
"= 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross",
"# print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover",
"from test_genetic_algorithm import TestGeneticAlgorithm from hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import numpy",
"rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) #",
"ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) #",
"= ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc =",
"ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) #",
"TestGeneticAlgorithm from hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import numpy as np ###",
"print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover =",
"# egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga =",
"0, 1, 0, 0, 0, 1, 1]]) beale_init_pop = np.array([[1, 0, 1, 0,",
"print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected",
"rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected)",
"Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0,",
"= 0.9, pm = 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast,",
"print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected",
"print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm",
"print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5,",
"1], [1, 0, 0, 0, 1, 0, 0, 1]]) egg_init_pop = np.array([[1, 0,",
"ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga =",
"1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1,",
"1], [1, 0, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0,",
"1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 0], [1,",
"egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc",
"0, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0,",
"1, 0], [0, 1, 1, 0, 1, 1, 1, 1], [1, 0, 1,",
"1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1,",
"= ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc = 0.9, pm",
"1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 1], [1, 0,",
"ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc = 0.9,",
"print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected",
"print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop)",
"elitism = 0.4) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) #",
"0, 0, 1, 1]]) beale_init_pop = np.array([[1, 0, 1, 0, 0, 0, 0,",
"ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop)",
"print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected",
"rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0)",
"0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) #",
"selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"tournament\")",
"### Proportional selection, elitism # ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5,",
"= ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover))",
"[1, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0,",
"egg_init_pop = np.array([[1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1,",
"= 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross))",
"himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) #",
"ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop)",
"1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 1,",
"ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop)",
"0, 0, 0, 1, 1]]) beale_init_pop = np.array([[1, 0, 1, 0, 0, 0,",
"= TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm = 0.5, max_iter=10) rast",
"1, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 1,",
"= np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1,",
"1, 1, 0]]) himme_init_pop = np.array([[1, 1, 0, 1, 1, 0, 1, 0],",
"ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga = TestGeneticAlgorithm(pc",
"1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0, 1,",
"0.9, pm = 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop)",
"1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1],",
"0, 1, 0, 0, 1]]) egg_init_pop = np.array([[1, 0, 1, 0, 1, 1,",
"1], [1, 0, 0, 0, 0, 1, 1, 0]]) himme_init_pop = np.array([[1, 1,",
"Tournament selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection =",
"0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0,",
"# print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga = TestGeneticAlgorithm(pc = 0.9, pm",
"1, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 1]]) egg_init_pop",
"1]]) egg_init_pop = np.array([[1, 0, 1, 0, 1, 1, 0, 0, 0, 0,",
"beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected =",
"0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2,",
"0, 0], [0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0,",
"elitism # ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism =",
"0, 0, 1, 1, 0]]) himme_init_pop = np.array([[1, 1, 0, 1, 1, 0,",
"np.array([[1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0,",
"1, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 0, 1,",
"egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga = TestGeneticAlgorithm(pc",
"1, 1], [1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 0,",
"print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop)",
"ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc = 0.9, pm =",
"0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]]) # print(rast_init_pop)",
"1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1], [0,",
"= ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga =",
"print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm",
"= \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross))",
"= 0.9, pm = 0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop) # rast_selected",
"print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover))",
"1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0,",
"himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop)",
"### SUS selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection",
"# himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected =",
"= TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected",
"elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm = 0.5,",
"# print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0])",
"1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 0, 1, 1]])",
"= ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0])",
"egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga",
"= ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop)",
"pm = 0.5, max_iter=10, elitism = 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected =",
"0, 0], [0, 0, 1, 1, 0, 1, 1, 0], [0, 1, 0,",
"Beale, Himmelblau, Eggholder import numpy as np ### Proportional selection, no elitism ga",
"1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1,",
"[1, 0, 1, 0, 0, 0, 1, 1]]) beale_init_pop = np.array([[1, 0, 1,",
"max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0])",
"1, 0, 0], [0, 1, 1, 0, 0, 1, 1, 1, 1, 1,",
"0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1,",
"0.4) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross =",
"0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross =",
"1, 1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0,",
"egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc = 0.9,",
"Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0, 1, 1, 1,",
"1, 0], [0, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0,",
"0]]) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross =",
"# rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross)",
"0, 1], [1, 0, 1, 0, 0, 0, 1, 1]]) beale_init_pop = np.array([[1,",
"0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1,",
"0, 1, 1, 0, 1, 0]]) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop)",
"0, 1, 0]]) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) #",
"1, 0, 1], [1, 0, 1, 0, 0, 0, 1, 1]]) beale_init_pop =",
"1, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1,",
"print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) #",
"0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 0,",
"ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover)",
"= ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w",
"0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,",
"0, 0, 0, 0, 1, 1, 0]]) himme_init_pop = np.array([[1, 1, 0, 1,",
"1, 1, 1, 0, 1, 1, 0, 1, 0]]) # print(rast_init_pop) # rast_selected",
"1, 0, 1, 1, 0, 1, 0]]) # print(rast_init_pop) # rast_selected = ga.select(rast,",
"0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 1,",
"1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1],",
"0, 0, 0], [0, 0, 1, 1, 0, 1, 1, 0], [0, 1,",
"0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 0],",
"[1, 0, 0, 0, 1, 0, 0, 1]]) egg_init_pop = np.array([[1, 0, 1,",
"= \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross))",
"Tournament selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10,",
"= TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected",
"# rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected =",
"ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga = TestGeneticAlgorithm(pc = 0.9,",
"print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) #",
"# print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected)",
"from hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import numpy as np ### Proportional",
"beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected)",
"1, 1, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1,",
"0.9, pm = 0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop) # rast_selected =",
"= 0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop)",
"1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0,",
"# print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0])",
"beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover =",
"= 0.9, pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0)",
"test_genetic_algorithm import TestGeneticAlgorithm from hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import numpy as",
"Eggholder import numpy as np ### Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149,",
"n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1,",
"1], [1, 0, 1, 0, 0, 0, 1, 1]]) beale_init_pop = np.array([[1, 0,",
"TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm = 0.5, max_iter=10) rast =",
"1, 0], [1, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1,",
"1, 0, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1], [1,",
"pc = 0.9, pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale =",
"TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected =",
"0], [1, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0,",
"print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) #",
"pm = 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected)",
"0.9, pm = 0.5, max_iter=10, elitism = 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected",
"print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism",
"print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga =",
"= ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover))",
"0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg",
"0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], [0,",
"= TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected",
"max_iter=10, elitism = 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected)",
"elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4)",
"print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ###",
"### Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc =",
"ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop)",
"egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga",
"0], [0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1,",
"1, 1, 0, 1, 0]]) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) #",
"# print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) #",
"= 0.5, max_iter=10, elitism = 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast,",
"0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 1, 1,",
"print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10,",
"### Tournament selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection",
"0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 1, 0],",
"# beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover)",
"0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1,",
"\"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop)",
"0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross =",
"ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) #",
"0, 1, 1]]) beale_init_pop = np.array([[1, 0, 1, 0, 0, 0, 0, 0],",
"ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) #",
"= ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover))",
"import numpy as np ### Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111,",
"1, 0, 0, 1]]) egg_init_pop = np.array([[1, 0, 1, 0, 1, 1, 0,",
"# egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism #",
"egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection",
"ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism",
"selection, elitism # ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism",
"0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0,",
"# beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected =",
"# ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4)",
"pm = 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected)",
"pm = 0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop) # rast_selected = ga.select(rast,",
"ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm = 0.5, max_iter=10)",
"1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1,",
"np.array([[1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0,",
"0, 1], [1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1,",
"0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1],",
"# print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected)",
"0.31915886, 0.45725239]], pc = 0.9, pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0)",
"print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga = TestGeneticAlgorithm(pc = 0.9,",
"beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) #",
"ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop)",
"print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS",
"# print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) #",
"1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0,",
"print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm =",
"egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0, 1, 1, 1, 1],",
"1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0,",
"[0, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0,",
"w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism =",
"max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0])",
"ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4, selection",
"print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover))",
"0, 0, 1, 1], [1, 0, 0, 0, 0, 1, 1, 0]]) himme_init_pop",
"0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1,",
"# print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5,",
"ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop)",
"print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover))",
"0, 0, 0, 1, 1, 0]]) himme_init_pop = np.array([[1, 1, 0, 1, 1,",
"egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament",
"[0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0,",
"Rastrigin, Beale, Himmelblau, Eggholder import numpy as np ### Proportional selection, no elitism",
"himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover =",
"1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0,",
"elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4,",
"0], [0, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0,",
"0, 0, 1, 0, 0, 1]]) egg_init_pop = np.array([[1, 0, 1, 0, 1,",
"0.4, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0])",
"1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 1],",
"print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc = 0.9, pm =",
"= Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0,",
"= ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w",
"= np.array([[1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1,",
"TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected =",
"0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0,",
"rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover =",
"himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected =",
"rast_init_pop = np.array([[1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1,",
"egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional",
"= 0.9, pm = 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast,",
"Proportional selection, elitism # ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10,",
"pm = 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected)",
"import TestGeneticAlgorithm from hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import numpy as np",
"= Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0, 1, 1,",
"= ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga = TestGeneticAlgorithm(pc =",
"# print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0])",
"# print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc = 0.9, pm",
"selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross)",
"1, 1], [1, 0, 0, 0, 0, 1, 1, 0]]) himme_init_pop = np.array([[1,",
"print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga =",
"hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import numpy as np ### Proportional selection,",
"1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 1, 1, 0,",
"0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 1]]) egg_init_pop =",
"egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga",
"0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1,",
"Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0, 1, 1, 1, 1], [1, 1,",
"0, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 1], [1,",
"print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament",
"print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) #",
"beale_init_pop) # print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop)",
"= ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme,",
"= ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross))",
"1, 1], [1, 0, 1, 1, 1, 0, 1, 1], [1, 0, 0,",
"SUS selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection =",
"1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 0, 1, 0,",
"print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover",
"selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm",
"# print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection,",
"beale_init_pop = np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1,",
"0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1,",
"# print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection",
"0, 1, 1, 1, 0, 1, 1, 0, 1, 0]]) # print(rast_init_pop) #",
"ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) #",
"1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 0,",
"1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0,",
"selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"sus\")",
"### SUS selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5,",
"TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected =",
"0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1,",
"1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 0,",
"[0, 1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1,",
"himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg,",
"[1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 0,",
"np.array([[1, 1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1,",
"ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4) #",
"1, 0]]) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross",
"1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1,",
"= ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale,",
"0, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0,",
"# print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga = TestGeneticAlgorithm(pc =",
"0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0,",
"0, 1, 1], [1, 0, 0, 0, 0, 1, 1, 0]]) himme_init_pop =",
"print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected",
"0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 1, 1, 0]])",
"# print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected)",
"1, 1, 1, 1], [1, 0, 1, 1, 1, 0, 1, 1], [1,",
"ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ###",
"= TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4, selection =",
"# print(beale_selected) # beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) #",
"1, 1, 1], [1, 0, 1, 1, 1, 0, 1, 1], [1, 0,",
"0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 0, 1,",
"1, 1, 0, 1, 1, 0, 1, 0]]) # print(rast_init_pop) # rast_selected =",
"= Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0, 1, 1, 1, 1], [1,",
"1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 0, 1,",
"egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) #",
"= 0.9, pm = 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast,",
"1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1,",
"0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,",
"# himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) # print(himme_crossover)",
"1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0,",
"max_iter=10, elitism = 0.4) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected)",
"print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover =",
"pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme =",
"1, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0,",
"1, 0, 1, 0]]) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected)",
"\"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop)",
"0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 1], [1, 0,",
"0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross =",
"1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 0], [1, 1,",
"beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0,",
"rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale,",
"0, 1, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1,",
"0], [0, 1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 1,",
"0], [0, 0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 0,",
"[1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1,",
"1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1,",
"1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],",
"1, 0, 0, 0, 1, 1]]) beale_init_pop = np.array([[1, 0, 1, 0, 0,",
"max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg =",
"1, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 0,",
"1], [1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1,",
"= TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop)",
"print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc =",
"0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1,",
"himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop = np.array([[1, 0, 0, 0, 1,",
"himme_init_pop = np.array([[1, 1, 0, 1, 1, 0, 1, 0], [0, 1, 1,",
"0, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1], [1, 0,",
"SUS selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10,",
"0, 1, 0, 1], [1, 0, 1, 0, 0, 0, 1, 1]]) beale_init_pop",
"= np.array([[1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0,",
"0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 1, 0], [0,",
"selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross)",
"egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection",
"0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0, 1, 1],",
"1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 1, 1,",
"beale_crossover = ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme,",
"1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 1, 1, 1,",
"[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,",
"1, 0]]) himme_init_pop = np.array([[1, 1, 0, 1, 1, 0, 1, 0], [0,",
"1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]])",
"elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross)",
"1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1,",
"1, 1]]) beale_init_pop = np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0,",
"1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0,",
"print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover",
"= 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross",
"no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc = 0.9, pm =",
"0, 1]]) egg_init_pop = np.array([[1, 0, 1, 0, 1, 1, 0, 0, 0,",
"= np.array([[1, 1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 0,",
"0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1,",
"= 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0)",
"ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) #",
"ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism",
"= ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg,",
"0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]]) #",
"[1, 0, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 1,",
"1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 1,",
"1]]) beale_init_pop = np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0, 0,",
"0, 0, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 1],",
"= 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross =",
"print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) #",
"print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop) # print(himme_selected) # himme_crossover = ga.crossover(himme_selected[0]) #",
"= Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop",
"himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected)",
"print(ga.mutate(egg_crossover)) ### SUS selection ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10,",
"1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1,",
"0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 1], [1,",
"= ga.crossover(himme_selected[0]) # print(himme_crossover) # print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop)",
"= ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0])",
"print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected",
"ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0]) print(beale_crossover)",
"ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### Tournament selection w elitism ga = TestGeneticAlgorithm(pc = 0.9,",
"0, 1], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0,",
"0.9, pm = 0.5, max_iter=10) rast = Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme",
"egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga = TestGeneticAlgorithm(pc",
"rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected =",
"elitism = 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross",
"= ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga = TestGeneticAlgorithm(pc =",
"print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) #",
"0, 1, 1, 0]]) himme_init_pop = np.array([[1, 1, 0, 1, 1, 0, 1,",
"import Rastrigin, Beale, Himmelblau, Eggholder import numpy as np ### Proportional selection, no",
"TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4) # print(rast_init_pop) #",
"= 0.5, max_iter=10, selection = \"sus\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross",
"0.9, pm = 0.5, max_iter=10, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop)",
"print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga",
"print(ga.mutate(egg_crossover)) ### Proportional selection, elitism # ga = TestGeneticAlgorithm(pc = 0.9, pm =",
"0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0,",
"0.5, max_iter=10, elitism = 0.4, selection = \"tournament\") print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop)",
"[1, 0, 0, 0, 0, 1, 1, 0]]) himme_init_pop = np.array([[1, 1, 0,",
"egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover) # print(ga.mutate(egg_crossover)) ### Tournament selection ga = TestGeneticAlgorithm(pc",
"max_iter=10, elitism = 0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0])",
"print(ga.mutate(egg_crossover)) ### SUS selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm =",
"0, 1, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 0,",
"# egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0]) # print(egg_crossover)",
"0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1], [1,",
"= ga.crossover(beale_selected[0]) # print(beale_crossover) # print(ga.mutate(beale_crossover)) # print(himme_init_pop) # himme_selected = ga.select(himme, himme_init_pop)",
"<reponame>leguiart/Evolutionary_Computing from test_genetic_algorithm import TestGeneticAlgorithm from hklearn_genetic.problem import Rastrigin, Beale, Himmelblau, Eggholder import",
"Himmelblau, Eggholder import numpy as np ### Proportional selection, no elitism ga =",
"TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism = 0.4, selection = \"tournament\")",
"selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5, max_iter=10, elitism",
"as np ### Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]],",
"print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover =",
"1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1,",
"1, 0, 1], [1, 0, 0, 0, 0, 1, 0, 1, 0, 1,",
"### Tournament selection w elitism ga = TestGeneticAlgorithm(pc = 0.9, pm = 0.5,",
"0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1, 1,",
"= 0.4) # print(rast_init_pop) # rast_selected = ga.select(rast, rast_init_pop) # print(rast_selected) # rast_cross",
"1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1,",
"1, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 1]])",
"rast_init_pop) # print(rast_selected) # rast_cross = ga.crossover(rast_selected[0]) # print(rast_cross) # print(ga.mutate(rast_cross)) # print(beale_init_pop)",
"0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 0, 1,",
"numpy as np ### Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886,",
"1], [1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 1,",
"0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0,",
"# print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover = ga.crossover(egg_selected[0])",
"[0, 0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0,",
"0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1,",
"ga.crossover(beale_selected[0]) print(beale_crossover) print(ga.mutate(beale_crossover)) print(himme_init_pop) himme_selected = ga.select(himme, himme_init_pop) print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover)",
"print(himme_selected) himme_crossover = ga.crossover(himme_selected[0]) print(himme_crossover) print(ga.mutate(himme_crossover)) print(egg_init_pop) egg_selected = ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover",
"np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0,",
"np ### Proportional selection, no elitism ga = TestGeneticAlgorithm([[0.25410149, 0.71410111, 0.31915886, 0.45725239]], pc",
"= ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop) beale_selected = ga.select(beale, beale_init_pop) print(beale_selected) beale_crossover = ga.crossover(beale_selected[0])",
"# print(ga.mutate(himme_crossover)) # print(egg_init_pop) # egg_selected = ga.select(egg, egg_init_pop) # print(egg_selected) # egg_crossover",
"# print(ga.mutate(rast_cross)) # print(beale_init_pop) # beale_selected = ga.select(beale, beale_init_pop) # print(beale_selected) # beale_crossover",
"1, 1], [1, 0, 0, 0, 1, 0, 0, 1]]) egg_init_pop = np.array([[1,",
"Rastrigin(n_dim=2, n_prec=0) beale = Beale(n_prec=0) himme = Himmelblau(n_prec=0) egg = Eggholder(n_prec=0) rast_init_pop =",
"0]]) himme_init_pop = np.array([[1, 1, 0, 1, 1, 0, 1, 0], [0, 1,",
"= ga.select(egg, egg_init_pop) print(egg_selected) egg_crossover = ga.crossover(egg_selected[0]) print(egg_crossover) print(ga.mutate(egg_crossover)) ### SUS selection ga",
"0.4) print(rast_init_pop) rast_selected = ga.select(rast, rast_init_pop) print(rast_selected) rast_cross = ga.crossover(rast_selected[0]) print(rast_cross) print(ga.mutate(rast_cross)) print(beale_init_pop)",
"0, 0, 1]]) egg_init_pop = np.array([[1, 0, 1, 0, 1, 1, 0, 0,",
"1, 0, 1], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0,"
] |
[
"'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors,",
"of ~3.5k rows for loc in self.get_truth_locations(): print('fetching %s...' % loc) # default",
"# only return missing atoms, i.e. locations that can't be further split atomic_locations",
"locations (i.e. a retrospective experiment) continue for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors,",
"flu data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of locations",
"to prevent cache misses on missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek,",
"rows for loc in self.get_truth_locations(): print('fetching %s...' % loc) # default to None",
"ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues",
"sensor_locations = set(self.get_sensor_locations()) # loop over locations to avoid hitting the limit of",
"for nowcasting. Caching is used extensively to reduce the number of requests made",
"def get_sensors(self): \"\"\"Return a list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self):",
"of weeks on which truth and sensors are both available.\"\"\" latest_week = self.get_most_recent_issue()",
"each sensor/location/epiweek data point individually. \"\"\" def extract(response): if response['result'] == -2: return",
"print('cache miss: get_truth_value', epiweek, location) auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth)",
"'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list)",
"in all locations FIRST_DATA_EPIWEEK = 201040 # all known sensors, past and present",
"\"\"\" def extract(response): if response['result'] == -2: return [] return self.epidata.check(response) weeks =",
"skip locations with no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili'])",
"if self.get_truth_value(epiweek, loc) is None: # this atomic location didn't report (or it's",
"(i.e. a retrospective experiment) continue for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen,",
"epidata self.sensors = sensors self.sensor_locations = locations # cache for prefetching bulk flu",
"location, epiweek, None) data = response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet', location,",
"Epidata API as used for nowcasting. Caching is used extensively to reduce the",
"hitting the limit of ~3.5k rows for loc in self.get_truth_locations(): print('fetching %s...' %",
"try: return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek, location, name) response =",
"if response['result'] != 1: return self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value'] return",
"self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek, location) auth = secrets.api.fluview response =",
"of locations in which ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self):",
"list of locations in which ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def",
"value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the",
"\"\"\"The interface by which all input data is provided.\"\"\" # the first epiweek",
"(and faster) than querying each sensor/location/epiweek data point individually. \"\"\" def extract(response): if",
"loop over locations to avoid hitting the limit of ~3.5k rows for loc",
"the cache.\"\"\" if name not in self.cache: self.cache[name] = {} if location not",
"def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata",
"only return missing atoms, i.e. locations that can't be further split atomic_locations =",
"def get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except",
"missing atoms, i.e. locations that can't be further split atomic_locations = set(Locations.atom_list) available_locations",
"it's a future week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations)) else:",
"the first epiweek for which we have ground truth ILI in all locations",
"list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except",
"is significantly more efficient (and faster) than querying each sensor/location/epiweek data point individually.",
"auth=secrets.api.fluview) for row in extract(response): # skip locations with no reporters if row['num_providers']",
"row['wili']) # sensor readings if loc not in sensor_locations: # skip withheld locations",
"the API. \"\"\" # standard library import functools # first party from delphi.epidata.client.delphi_epidata",
"for the Epidata API as used for nowcasting. Caching is used extensively to",
"over locations to avoid hitting the limit of ~3.5k rows for loc in",
"['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource(",
"than querying each sensor/location/epiweek data point individually. \"\"\" def extract(response): if response['result'] ==",
"available_locations: return tuple(atomic_locations - set(available_locations)) else: # no data is available, assume that",
"= {} if location not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value",
"class FluDataSource(DataSource): \"\"\"The interface by which all input data is provided.\"\"\" # the",
"in self.cache: self.cache[name] = {} if location not in self.cache[name]: self.cache[name][location] = {}",
"= [] for loc in atomic_locations: if self.get_truth_value(epiweek, loc) is None: # this",
"epiweek): \"\"\"Return a tuple of locations which did not report on the given",
"epidata, sensors, locations): self.epidata = epidata self.sensors = sensors self.sensor_locations = locations #",
"= range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground",
"functools # first party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource from",
"data point individually. \"\"\" def extract(response): if response['result'] == -2: return [] return",
"epiweek, auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek, None) data =",
"0: return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def",
"individually. \"\"\" def extract(response): if response['result'] == -2: return [] return self.epidata.check(response) weeks",
"new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata =",
"<filename>src/util/flu_data_source.py \"\"\" =============== === Purpose === =============== A wrapper for the Epidata API",
"def get_most_recent_issue(self): \"\"\"Return the most recent epiweek for which FluView data is available.\"\"\"",
"a future week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations)) else: #",
"self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value return value def prefetch(self, epiweek): \"\"\"",
"'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self,",
"for row in extract(response): # skip locations with no reporters if row['num_providers'] >",
"\"\"\" Fetch all data in all locations up to the given epiweek. Requests",
"secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet', location,",
"get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache",
"week, None) # ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in",
"extract(response): if response['result'] == -2: return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek)",
"experiment) continue for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for",
"value return value def prefetch(self, epiweek): \"\"\" Fetch all data in all locations",
"skip withheld locations (i.e. a retrospective experiment) continue for sen in self.get_sensors(): response",
"list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of",
"ILI in all locations FIRST_DATA_EPIWEEK = 201040 # all known sensors, past and",
"truth and sensors are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK,",
"get_truth_value', epiweek, location) auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if response['result']",
"@functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def",
"epiweek, location) auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if response['result'] !=",
"@functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent epiweek for which FluView data is",
"reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek, location, name) response",
"self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings if loc not in sensor_locations: #",
"data is provided.\"\"\" # the first epiweek for which we have ground truth",
"to the given epiweek. Requests are batched. This is significantly more efficient (and",
"\"\"\" # standard library import functools # first party from delphi.epidata.client.delphi_epidata import Epidata",
"except KeyError: print('cache miss: get_truth_value', epiweek, location) auth = secrets.api.fluview response = self.epidata.fluview(location,",
"the number of requests made to the API. \"\"\" # standard library import",
"get_sensors(self): \"\"\"Return a list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return",
"= self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for row in self.epidata.check(response)] return max(issues)",
"location, epiweek, value): \"\"\"Add the given value to the cache.\"\"\" if name not",
"weeks on which truth and sensors are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range",
"self.get_truth_locations(): print('fetching %s...' % loc) # default to None to prevent cache misses",
"are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return",
"report on the given week.\"\"\" # only return missing atoms, i.e. locations that",
"import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource):",
"epiweek. Requests are batched. This is significantly more efficient (and faster) than querying",
"row['epiweek'], row['wili']) # sensor readings if loc not in sensor_locations: # skip withheld",
"and sensors are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week,",
"= self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek,",
"in self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location, epiweek, value): \"\"\"Add the given",
"delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets from delphi.utils.epidate",
"can't be further split atomic_locations = set(Locations.atom_list) available_locations = [] for loc in",
"auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1: return",
"loc in self.get_truth_locations(): print('fetching %s...' % loc) # default to None to prevent",
"epiweek, None) data = response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek,",
"continue for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row",
"sensors, locations): self.epidata = epidata self.sensors = sensors self.sensor_locations = locations # cache",
"is used extensively to reduce the number of requests made to the API.",
"faster) than querying each sensor/location/epiweek data point individually. \"\"\" def extract(response): if response['result']",
"=== Purpose === =============== A wrapper for the Epidata API as used for",
"epiweek for which we have ground truth ILI in all locations FIRST_DATA_EPIWEEK =",
"# skip locations with no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'],",
"values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet'] +",
"response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row in extract(response): self.add_to_cache(sen, loc, row['epiweek'],",
"if location not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value return value",
"name not in self.cache: self.cache[name] = {} if location not in self.cache[name]: self.cache[name][location]",
"201040 # all known sensors, past and present SENSORS = ['gft', 'ght', 'twtr',",
"continue available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations)) else: # no data is",
"to reduce the number of requests made to the API. \"\"\" # standard",
"response = self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek,",
"reduce the number of requests made to the API. \"\"\" # standard library",
"a retrospective experiment) continue for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc,",
"tuple of locations which did not report on the given week.\"\"\" # only",
"interface by which all input data is provided.\"\"\" # the first epiweek for",
"from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations",
"cache.\"\"\" if name not in self.cache: self.cache[name] = {} if location not in",
"= sensors self.sensor_locations = locations # cache for prefetching bulk flu data self.cache",
"SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance():",
"more efficient (and faster) than querying each sensor/location/epiweek data point individually. \"\"\" def",
"self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek, None) data",
"most recent epiweek for which FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1",
"of requests made to the API. \"\"\" # standard library import functools #",
"week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations)) else: # no data",
"-2: return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) #",
"first party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import",
"data = response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek, None) return",
"location) auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1:",
"which truth and sensors are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks(",
"{} self.cache[name][location][epiweek] = value return value def prefetch(self, epiweek): \"\"\" Fetch all data",
"self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over locations to",
"split atomic_locations = set(Locations.atom_list) available_locations = [] for loc in atomic_locations: if self.get_truth_value(epiweek,",
"= locations # cache for prefetching bulk flu data self.cache = {} @functools.lru_cache(maxsize=1)",
"avoid hitting the limit of ~3.5k rows for loc in self.get_truth_locations(): print('fetching %s...'",
"\"\"\" =============== === Purpose === =============== A wrapper for the Epidata API as",
"def get_truth_locations(self): \"\"\"Return a list of locations in which ground truth is available.\"\"\"",
"ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of",
"= add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for row",
"get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError:",
"data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat',",
"-9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for row in self.epidata.check(response)]",
"all locations FIRST_DATA_EPIWEEK = 201040 # all known sensors, past and present SENSORS",
"= self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row in extract(response): self.add_to_cache(sen, loc, row['epiweek'], row['value'])",
"input data is provided.\"\"\" # the first epiweek for which we have ground",
"reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings if",
"for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet'] + self.get_sensors():",
"FluDataSource(DataSource): \"\"\"The interface by which all input data is provided.\"\"\" # the first",
"This is significantly more efficient (and faster) than querying each sensor/location/epiweek data point",
"self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of weeks on which truth and",
"did not report on the given week.\"\"\" # only return missing atoms, i.e.",
"latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try:",
"in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row in extract(response): self.add_to_cache(sen,",
"prefetching bulk flu data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list",
"epiweek, location, name): \"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache",
"that all locations will be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a",
"\"\"\"Return the most recent epiweek for which FluView data is available.\"\"\" ew2 =",
"which all input data is provided.\"\"\" # the first epiweek for which we",
"querying each sensor/location/epiweek data point individually. \"\"\" def extract(response): if response['result'] == -2:",
"further split atomic_locations = set(Locations.atom_list) available_locations = [] for loc in atomic_locations: if",
"add_to_cache(self, name, location, epiweek, value): \"\"\"Add the given value to the cache.\"\"\" if",
"this atomic location didn't report (or it's a future week) continue available_locations.append(loc) if",
"didn't report (or it's a future week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations",
"cache for prefetching bulk flu data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return",
"week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return",
"row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings if loc not",
"sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of weeks on",
"return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of locations in which sensors",
"given epiweek. Requests are batched. This is significantly more efficient (and faster) than",
"return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek, location, name) response = self.epidata.sensors(",
"name, location, epiweek, value): \"\"\"Add the given value to the cache.\"\"\" if name",
"return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over locations",
"future week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations)) else: # no",
"self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row in extract(response): self.add_to_cache(sen, loc,",
"self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet',",
"list of weeks on which truth and sensors are both available.\"\"\" latest_week =",
"KeyError: print('cache miss: get_truth_value', epiweek, location) auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek,",
"locations in which ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return",
"name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground truth response",
"add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for row in",
"return tuple(atomic_locations - set(available_locations)) else: # no data is available, assume that all",
"Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata = epidata self.sensors =",
"not in sensor_locations: # skip withheld locations (i.e. a retrospective experiment) continue for",
"'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata,",
"in all locations up to the given epiweek. Requests are batched. This is",
"return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of sensor names.\"\"\" return self.sensors",
"None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return",
"row in self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location, epiweek, value): \"\"\"Add the",
"None: # this atomic location didn't report (or it's a future week) continue",
"= {} self.cache[name][location][epiweek] = value return value def prefetch(self, epiweek): \"\"\" Fetch all",
"nowcasting. Caching is used extensively to reduce the number of requests made to",
"self.cache[name][location][epiweek] = value return value def prefetch(self, epiweek): \"\"\" Fetch all data in",
"auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0]",
"all locations up to the given epiweek. Requests are batched. This is significantly",
"available_locations = [] for loc in atomic_locations: if self.get_truth_value(epiweek, loc) is None: #",
"on which truth and sensors are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range =",
"'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata,",
"Fetch all data in all locations up to the given epiweek. Requests are",
"in atomic_locations: if self.get_truth_value(epiweek, loc) is None: # this atomic location didn't report",
"self.add_to_cache(name, loc, week, None) # ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for",
"data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili'])",
"which we have ground truth ILI in all locations FIRST_DATA_EPIWEEK = 201040 #",
"self.epidata.range(ew1, ew2)) issues = [row['issue'] for row in self.epidata.check(response)] return max(issues) def add_to_cache(self,",
"epiweek): \"\"\" Fetch all data in all locations up to the given epiweek.",
"response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location,",
"return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of weeks on which truth",
"known sensors, past and present SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic',",
"significantly more efficient (and faster) than querying each sensor/location/epiweek data point individually. \"\"\"",
"available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def",
"0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings if loc not in sensor_locations:",
"i.e. locations that can't be further split atomic_locations = set(Locations.atom_list) available_locations = []",
"batched. This is significantly more efficient (and faster) than querying each sensor/location/epiweek data",
"!= 1: return self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location,",
"in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground truth response =",
"= response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most",
"return max(issues) def add_to_cache(self, name, location, epiweek, value): \"\"\"Add the given value to",
"and present SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod",
"is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1,",
"epiweek, inclusive=True): for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None) #",
"of locations which did not report on the given week.\"\"\" # only return",
"def get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError:",
"the given week.\"\"\" # only return missing atoms, i.e. locations that can't be",
"both available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range)",
"in extract(response): # skip locations with no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet',",
"in sensor_locations: # skip withheld locations (i.e. a retrospective experiment) continue for sen",
"in which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a",
"location, name): \"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache miss:",
"get_sensor_value', epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result']",
"print('cache miss: get_sensor_value', epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek)",
"location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor reading.\"\"\"",
"@functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations which did not report",
"prefetch(self, epiweek): \"\"\" Fetch all data in all locations up to the given",
"extract(response): # skip locations with no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc,",
"return self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0] if data['num_providers'] == 0: return",
"name) response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result'] != 1: return",
"Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata = epidata self.sensors = sensors self.sensor_locations",
"are batched. This is significantly more efficient (and faster) than querying each sensor/location/epiweek",
"to avoid hitting the limit of ~3.5k rows for loc in self.get_truth_locations(): print('fetching",
"range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground truth",
"DataSource from delphi.operations import secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks,",
"== -2: return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations())",
"names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of weeks on which",
"(or it's a future week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations))",
"get_sensor_locations(self): \"\"\"Return a list of locations in which sensors are available.\"\"\" return self.sensor_locations",
"location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value',",
"+ self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground truth response = self.epidata.fluview(loc, weeks,",
"sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row in extract(response):",
"not in self.cache: self.cache[name] = {} if location not in self.cache[name]: self.cache[name][location] =",
"FIRST_DATA_EPIWEEK = 201040 # all known sensors, past and present SENSORS = ['gft',",
"FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None)",
"{} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of locations in which ground truth",
"as used for nowcasting. Caching is used extensively to reduce the number of",
"a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek, location,",
"epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor reading.\"\"\" try:",
"loc not in sensor_locations: # skip withheld locations (i.e. a retrospective experiment) continue",
"= 201040 # all known sensors, past and present SENSORS = ['gft', 'ght',",
"the Epidata API as used for nowcasting. Caching is used extensively to reduce",
"ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response): # skip",
"provided.\"\"\" # the first epiweek for which we have ground truth ILI in",
"are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations",
"self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor",
"self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent epiweek for",
"import Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets from delphi.utils.epidate import",
"available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations which",
"= self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response): # skip locations with no",
"else: # no data is available, assume that all locations will be reporting",
"epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result'] !=",
"Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets from delphi.utils.epidate import EpiDate",
"return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self,",
"for row in self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location, epiweek, value): \"\"\"Add",
"epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name):",
"max(issues) def add_to_cache(self, name, location, epiweek, value): \"\"\"Add the given value to the",
"issues = [row['issue'] for row in self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location,",
"# default to None to prevent cache misses on missing values for week",
"loc) is None: # this atomic location didn't report (or it's a future",
"== 0: return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None)",
"is None: # this atomic location didn't report (or it's a future week)",
"self.get_truth_value(epiweek, loc) is None: # this atomic location didn't report (or it's a",
"[] for loc in atomic_locations: if self.get_truth_value(epiweek, loc) is None: # this atomic",
"cache misses on missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for",
"have ground truth ILI in all locations FIRST_DATA_EPIWEEK = 201040 # all known",
"set(Locations.atom_list) available_locations = [] for loc in atomic_locations: if self.get_truth_value(epiweek, loc) is None:",
"up to the given epiweek. Requests are batched. This is significantly more efficient",
"response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for row in self.epidata.check(response)] return",
"= {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of locations in which ground",
"will be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of sensor",
"is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of locations in",
"first epiweek for which we have ground truth ILI in all locations FIRST_DATA_EPIWEEK",
"report (or it's a future week) continue available_locations.append(loc) if available_locations: return tuple(atomic_locations -",
"# this atomic location didn't report (or it's a future week) continue available_locations.append(loc)",
"by which all input data is provided.\"\"\" # the first epiweek for which",
"location didn't report (or it's a future week) continue available_locations.append(loc) if available_locations: return",
"location, epiweek) if response['result'] != 1: return self.add_to_cache(name, location, epiweek, None) value =",
"\"\"\"Return a list of locations in which ground truth is available.\"\"\" return Locations.region_list",
"> 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings if loc not in",
"location, epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def",
"in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value return value def prefetch(self, epiweek):",
"\"\"\"Return a list of locations in which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None)",
"response['result'] == -2: return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations =",
"FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata = epidata self.sensors = sensors",
"# standard library import functools # first party from delphi.epidata.client.delphi_epidata import Epidata from",
"epiweek, value): \"\"\"Add the given value to the cache.\"\"\" if name not in",
"self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location):",
"ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek, location)",
"\"\"\"Add the given value to the cache.\"\"\" if name not in self.cache: self.cache[name]",
"# the first epiweek for which we have ground truth ILI in all",
"a list of weeks on which truth and sensors are both available.\"\"\" latest_week",
"all locations will be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list",
"present SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def",
"sensor/location/epiweek data point individually. \"\"\" def extract(response): if response['result'] == -2: return []",
"epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent epiweek for which FluView",
"all data in all locations up to the given epiweek. Requests are batched.",
"(w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek, location) auth =",
"= response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet',",
"@functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek]",
"readings if loc not in sensor_locations: # skip withheld locations (i.e. a retrospective",
"data is available, assume that all locations will be reporting return () @functools.lru_cache(maxsize=1)",
"# sensor readings if loc not in sensor_locations: # skip withheld locations (i.e.",
"withheld locations (i.e. a retrospective experiment) continue for sen in self.get_sensors(): response =",
"Requests are batched. This is significantly more efficient (and faster) than querying each",
"from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface",
"Caching is used extensively to reduce the number of requests made to the",
"=============== === Purpose === =============== A wrapper for the Epidata API as used",
"self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of locations in which",
"secrets.api.sensors, name, location, epiweek) if response['result'] != 1: return self.add_to_cache(name, location, epiweek, None)",
"1: return self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek,",
"delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface by which all input data is",
"\"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek,",
"retrospective experiment) continue for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks)",
"ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for",
"missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet']",
"bulk flu data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of",
"self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response): # skip locations with no reporters",
"inclusive=True): for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground",
"atomic_locations = set(Locations.atom_list) available_locations = [] for loc in atomic_locations: if self.get_truth_value(epiweek, loc)",
"API. \"\"\" # standard library import functools # first party from delphi.epidata.client.delphi_epidata import",
"[] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over",
"locations up to the given epiweek. Requests are batched. This is significantly more",
"loc, row['epiweek'], row['wili']) # sensor readings if loc not in sensor_locations: # skip",
"self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result'] != 1: return self.add_to_cache(name, location, epiweek,",
"Locations class FluDataSource(DataSource): \"\"\"The interface by which all input data is provided.\"\"\" #",
"EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue']",
"{} if location not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value return",
"for sen in self.get_sensors(): response = self.epidata.sensors(secrets.api.sensors, sen, loc, weeks) for row in",
"delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class",
"= value return value def prefetch(self, epiweek): \"\"\" Fetch all data in all",
"1: return self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0] if data['num_providers'] == 0:",
"location not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value return value def",
"epiweek for which FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2,",
"loc) # default to None to prevent cache misses on missing values for",
"sensor readings if loc not in sensor_locations: # skip withheld locations (i.e. a",
"@functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of weeks on which truth and sensors",
"list of locations in which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self,",
"locations that can't be further split atomic_locations = set(Locations.atom_list) available_locations = [] for",
"be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of sensor names.\"\"\"",
"atomic location didn't report (or it's a future week) continue available_locations.append(loc) if available_locations:",
"self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues = [row['issue'] for row in self.epidata.check(response)] return max(issues) def",
"ground truth ILI in all locations FIRST_DATA_EPIWEEK = 201040 # all known sensors,",
"%s...' % loc) # default to None to prevent cache misses on missing",
"ew2)) issues = [row['issue'] for row in self.epidata.check(response)] return max(issues) def add_to_cache(self, name,",
"in which ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a",
"if name not in self.cache: self.cache[name] = {} if location not in self.cache[name]:",
"delphi.operations import secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from",
"get_most_recent_issue(self): \"\"\"Return the most recent epiweek for which FluView data is available.\"\"\" ew2",
"self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1)",
"wrapper for the Epidata API as used for nowcasting. Caching is used extensively",
"import functools # first party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource",
"def __init__(self, epidata, sensors, locations): self.epidata = epidata self.sensors = sensors self.sensor_locations =",
"which did not report on the given week.\"\"\" # only return missing atoms,",
"EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The",
"% loc) # default to None to prevent cache misses on missing values",
"self.sensor_locations = locations # cache for prefetching bulk flu data self.cache = {}",
"delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek",
"return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations which did",
"= ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return",
"!= 1: return self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0] if data['num_providers'] ==",
"available, assume that all locations will be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self):",
"to None to prevent cache misses on missing values for week in range_epiweeks(",
"# no data is available, assume that all locations will be reporting return",
"print('fetching %s...' % loc) # default to None to prevent cache misses on",
"'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def",
"is available, assume that all locations will be reporting return () @functools.lru_cache(maxsize=1) def",
"which ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list",
"for prefetching bulk flu data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a",
"latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self,",
"= set(Locations.atom_list) available_locations = [] for loc in atomic_locations: if self.get_truth_value(epiweek, loc) is",
"number of requests made to the API. \"\"\" # standard library import functools",
"- set(available_locations)) else: # no data is available, assume that all locations will",
"FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata = epidata self.sensors",
"if data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek,",
"return self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value)",
"set(self.get_sensor_locations()) # loop over locations to avoid hitting the limit of ~3.5k rows",
"be further split atomic_locations = set(Locations.atom_list) available_locations = [] for loc in atomic_locations:",
"= EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2)) issues =",
"used extensively to reduce the number of requests made to the API. \"\"\"",
"value to the cache.\"\"\" if name not in self.cache: self.cache[name] = {} if",
"Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over locations to avoid hitting the",
"for loc in self.get_truth_locations(): print('fetching %s...' % loc) # default to None to",
"return value def prefetch(self, epiweek): \"\"\" Fetch all data in all locations up",
"past and present SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch']",
"return missing atoms, i.e. locations that can't be further split atomic_locations = set(Locations.atom_list)",
"extensively to reduce the number of requests made to the API. \"\"\" #",
"@functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of locations in which ground truth is",
"in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc,",
"truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response): # skip locations",
"def extract(response): if response['result'] == -2: return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK,",
"a list of locations in which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def",
"locations): self.epidata = epidata self.sensors = sensors self.sensor_locations = locations # cache for",
"to the cache.\"\"\" if name not in self.cache: self.cache[name] = {} if location",
"available_locations.append(loc) if available_locations: return tuple(atomic_locations - set(available_locations)) else: # no data is available,",
"for which FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9)",
"data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return a sensor reading.\"\"\" try: return",
"atomic_locations: if self.get_truth_value(epiweek, loc) is None: # this atomic location didn't report (or",
"in self.get_truth_locations(): print('fetching %s...' % loc) # default to None to prevent cache",
"= self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek, None)",
"# loop over locations to avoid hitting the limit of ~3.5k rows for",
"miss: get_truth_value', epiweek, location) auth = secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if",
"get_weeks(self): \"\"\"Return a list of weeks on which truth and sensors are both",
"def get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations which did not report on",
"Purpose === =============== A wrapper for the Epidata API as used for nowcasting.",
"sensor_locations: # skip withheld locations (i.e. a retrospective experiment) continue for sen in",
"locations with no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) #",
"self.sensors = sensors self.sensor_locations = locations # cache for prefetching bulk flu data",
"\"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek,",
"truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of locations",
"sensors self.sensor_locations = locations # cache for prefetching bulk flu data self.cache =",
"response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0] if data['num_providers']",
"# skip withheld locations (i.e. a retrospective experiment) continue for sen in self.get_sensors():",
"for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground truth",
"of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list of weeks",
"= epidata self.sensors = sensors self.sensor_locations = locations # cache for prefetching bulk",
"party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets",
"\"\"\"Return a tuple of locations which did not report on the given week.\"\"\"",
"inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return",
"available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response = self.epidata.fluview('nat', self.epidata.range(ew1, ew2))",
"data in all locations up to the given epiweek. Requests are batched. This",
"# all known sensors, past and present SENSORS = ['gft', 'ght', 'twtr', 'wiki',",
"if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings if loc",
"a tuple of locations which did not report on the given week.\"\"\" #",
"return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek]",
"__init__(self, epidata, sensors, locations): self.epidata = epidata self.sensors = sensors self.sensor_locations = locations",
"assume that all locations will be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return",
"value): \"\"\"Add the given value to the cache.\"\"\" if name not in self.cache:",
"None) # ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response):",
"None to prevent cache misses on missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK,",
"self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors,",
"epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self):",
"given week.\"\"\" # only return missing atoms, i.e. locations that can't be further",
"the given value to the cache.\"\"\" if name not in self.cache: self.cache[name] =",
"None) value = response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return",
"locations which did not report on the given week.\"\"\" # only return missing",
"the most recent epiweek for which FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew()",
"return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location, name): \"\"\"Return a",
"= Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over locations to avoid hitting",
"a list of locations in which ground truth is available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1)",
"def add_to_cache(self, name, location, epiweek, value): \"\"\"Add the given value to the cache.\"\"\"",
"if loc not in sensor_locations: # skip withheld locations (i.e. a retrospective experiment)",
"return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop",
"is provided.\"\"\" # the first epiweek for which we have ground truth ILI",
"# ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response): #",
"the given epiweek. Requests are batched. This is significantly more efficient (and faster)",
"locations FIRST_DATA_EPIWEEK = 201040 # all known sensors, past and present SENSORS =",
"@functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of locations in which sensors are available.\"\"\"",
"to the API. \"\"\" # standard library import functools # first party from",
"locations to avoid hitting the limit of ~3.5k rows for loc in self.get_truth_locations():",
"available.\"\"\" return Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of locations in which",
"\"\"\"Return a list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a",
"miss: get_sensor_value', epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if",
"return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek, location) auth = secrets.api.fluview response",
"limit of ~3.5k rows for loc in self.get_truth_locations(): print('fetching %s...' % loc) #",
"if response['result'] != 1: return self.add_to_cache('ilinet', location, epiweek, None) data = response['epidata'][0] if",
"self.cache: self.cache[name] = {} if location not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek]",
"try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek, location) auth = secrets.api.fluview",
"Locations.region_list @functools.lru_cache(maxsize=1) def get_sensor_locations(self): \"\"\"Return a list of locations in which sensors are",
"used for nowcasting. Caching is used extensively to reduce the number of requests",
"truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss: get_truth_value', epiweek, location) auth",
"= [row['issue'] for row in self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location, epiweek,",
"week.\"\"\" # only return missing atoms, i.e. locations that can't be further split",
"row in extract(response): # skip locations with no reporters if row['num_providers'] > 0:",
"() @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1)",
"epiweek) if response['result'] != 1: return self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value']",
"except KeyError: print('cache miss: get_sensor_value', epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors, name,",
"weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over locations to avoid",
"= secrets.api.fluview response = self.epidata.fluview(location, epiweek, auth=auth) if response['result'] != 1: return self.add_to_cache('ilinet',",
"self.cache[name] = {} if location not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] =",
"sensors, past and present SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc', 'epic', 'sar3',",
"not report on the given week.\"\"\" # only return missing atoms, i.e. locations",
"loc, week, None) # ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row",
"self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location, epiweek, value): \"\"\"Add the given value",
"self.cache[name][location] = {} self.cache[name][location][epiweek] = value return value def prefetch(self, epiweek): \"\"\" Fetch",
"=============== A wrapper for the Epidata API as used for nowcasting. Caching is",
"given value to the cache.\"\"\" if name not in self.cache: self.cache[name] = {}",
"if response['result'] == -2: return [] return self.epidata.check(response) weeks = Epidata.range(FluDataSource.FIRST_DATA_EPIWEEK, epiweek) sensor_locations",
"standard library import functools # first party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast",
"the limit of ~3.5k rows for loc in self.get_truth_locations(): print('fetching %s...' % loc)",
"=== =============== A wrapper for the Epidata API as used for nowcasting. Caching",
"which FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response",
"range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week,",
"weeks, auth=secrets.api.fluview) for row in extract(response): # skip locations with no reporters if",
"loc in atomic_locations: if self.get_truth_value(epiweek, loc) is None: # this atomic location didn't",
"self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations which did not",
"# cache for prefetching bulk flu data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self):",
"None) data = response['epidata'][0] if data['num_providers'] == 0: return self.add_to_cache('ilinet', location, epiweek, None)",
"atoms, i.e. locations that can't be further split atomic_locations = set(Locations.atom_list) available_locations =",
"no data is available, assume that all locations will be reporting return ()",
"location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek, location,",
"sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value', epiweek, location, name)",
"location, name) response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result'] != 1:",
"FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 = add_epiweeks(ew2, -9) response =",
"efficient (and faster) than querying each sensor/location/epiweek data point individually. \"\"\" def extract(response):",
"data self.cache = {} @functools.lru_cache(maxsize=1) def get_truth_locations(self): \"\"\"Return a list of locations in",
"delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface by",
"epiweek) sensor_locations = set(self.get_sensor_locations()) # loop over locations to avoid hitting the limit",
"week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in ['ilinet'] + self.get_sensors(): self.add_to_cache(name,",
"secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import",
"response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview) for row in extract(response): # skip locations with",
"# first party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations",
"sensors are both available.\"\"\" latest_week = self.get_most_recent_issue() week_range = range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True)",
"def get_sensor_locations(self): \"\"\"Return a list of locations in which sensors are available.\"\"\" return",
"def prefetch(self, epiweek): \"\"\" Fetch all data in all locations up to the",
"prevent cache misses on missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True):",
"\"\"\"Return a list of weeks on which truth and sensors are both available.\"\"\"",
"of locations in which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek):",
"from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets from",
"not in self.cache[name]: self.cache[name][location] = {} self.cache[name][location][epiweek] = value return value def prefetch(self,",
"default to None to prevent cache misses on missing values for week in",
"import add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface by which",
"tuple(atomic_locations - set(available_locations)) else: # no data is available, assume that all locations",
"get_missing_locations(self, epiweek): \"\"\"Return a tuple of locations which did not report on the",
"'twtr', 'wiki', 'cdc', 'epic', 'sar3', 'arch'] @staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS,",
"on missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name in",
"def get_weeks(self): \"\"\"Return a list of weeks on which truth and sensors are",
"= self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result'] != 1: return self.add_to_cache(name, location,",
"add_epiweeks, range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface by which all",
"locations in which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return",
"location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent epiweek for which",
"misses on missing values for week in range_epiweeks( FluDataSource.FIRST_DATA_EPIWEEK, epiweek, inclusive=True): for name",
"for which we have ground truth ILI in all locations FIRST_DATA_EPIWEEK = 201040",
"from delphi.operations import secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks",
"= set(self.get_sensor_locations()) # loop over locations to avoid hitting the limit of ~3.5k",
"value def prefetch(self, epiweek): \"\"\" Fetch all data in all locations up to",
"locations will be reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of",
"['ilinet'] + self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground truth response = self.epidata.fluview(loc,",
"API as used for nowcasting. Caching is used extensively to reduce the number",
"reporting return () @functools.lru_cache(maxsize=1) def get_sensors(self): \"\"\"Return a list of sensor names.\"\"\" return",
"all known sensors, past and present SENSORS = ['gft', 'ght', 'twtr', 'wiki', 'cdc',",
"on the given week.\"\"\" # only return missing atoms, i.e. locations that can't",
"get_truth_locations(self): \"\"\"Return a list of locations in which ground truth is available.\"\"\" return",
"return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent epiweek",
"[row['issue'] for row in self.epidata.check(response)] return max(issues) def add_to_cache(self, name, location, epiweek, value):",
"value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent epiweek for which FluView data",
"for loc in atomic_locations: if self.get_truth_value(epiweek, loc) is None: # this atomic location",
"import Locations class FluDataSource(DataSource): \"\"\"The interface by which all input data is provided.\"\"\"",
"import DataSource from delphi.operations import secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import",
"all input data is provided.\"\"\" # the first epiweek for which we have",
"from delphi.nowcast.fusion.nowcast import DataSource from delphi.operations import secrets from delphi.utils.epidate import EpiDate from",
"self.epidata = epidata self.sensors = sensors self.sensor_locations = locations # cache for prefetching",
"with no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor",
"range_epiweeks from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface by which all input",
"which sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple",
"@staticmethod def new_instance(): return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations):",
"FluDataSource.FIRST_DATA_EPIWEEK, latest_week, inclusive=True) return list(week_range) def get_truth_value(self, epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\"",
"locations # cache for prefetching bulk flu data self.cache = {} @functools.lru_cache(maxsize=1) def",
"name): \"\"\"Return a sensor reading.\"\"\" try: return self.cache[name][location][epiweek] except KeyError: print('cache miss: get_sensor_value',",
"self.get_sensors(): self.add_to_cache(name, loc, week, None) # ground truth response = self.epidata.fluview(loc, weeks, auth=secrets.api.fluview)",
"no reporters if row['num_providers'] > 0: self.add_to_cache('ilinet', loc, row['epiweek'], row['wili']) # sensor readings",
"truth ILI in all locations FIRST_DATA_EPIWEEK = 201040 # all known sensors, past",
"we have ground truth ILI in all locations FIRST_DATA_EPIWEEK = 201040 # all",
"sensors are available.\"\"\" return self.sensor_locations @functools.lru_cache(maxsize=None) def get_missing_locations(self, epiweek): \"\"\"Return a tuple of",
"response = self.epidata.sensors( secrets.api.sensors, name, location, epiweek) if response['result'] != 1: return self.add_to_cache(name,",
"library import functools # first party from delphi.epidata.client.delphi_epidata import Epidata from delphi.nowcast.fusion.nowcast import",
"from delphi.utils.geo.locations import Locations class FluDataSource(DataSource): \"\"\"The interface by which all input data",
"set(available_locations)) else: # no data is available, assume that all locations will be",
"A wrapper for the Epidata API as used for nowcasting. Caching is used",
"made to the API. \"\"\" # standard library import functools # first party",
"epiweek, location): \"\"\"Return ground truth (w)ILI.\"\"\" try: return self.cache['ilinet'][location][epiweek] except KeyError: print('cache miss:",
"response['result'] != 1: return self.add_to_cache(name, location, epiweek, None) value = response['epidata'][0]['value'] return self.add_to_cache(name,",
"that can't be further split atomic_locations = set(Locations.atom_list) available_locations = [] for loc",
"return FluDataSource( Epidata, FluDataSource.SENSORS, Locations.region_list) def __init__(self, epidata, sensors, locations): self.epidata = epidata",
"recent epiweek for which FluView data is available.\"\"\" ew2 = EpiDate.today().get_ew() ew1 =",
"requests made to the API. \"\"\" # standard library import functools # first",
"name, location, epiweek) if response['result'] != 1: return self.add_to_cache(name, location, epiweek, None) value",
"a list of sensor names.\"\"\" return self.sensors @functools.lru_cache(maxsize=1) def get_weeks(self): \"\"\"Return a list",
"self.add_to_cache('ilinet', location, epiweek, None) return self.add_to_cache('ilinet', location, epiweek, data['wili']) @functools.lru_cache(maxsize=None) def get_sensor_value(self, epiweek,",
"point individually. \"\"\" def extract(response): if response['result'] == -2: return [] return self.epidata.check(response)",
"~3.5k rows for loc in self.get_truth_locations(): print('fetching %s...' % loc) # default to",
"KeyError: print('cache miss: get_sensor_value', epiweek, location, name) response = self.epidata.sensors( secrets.api.sensors, name, location,",
"response['epidata'][0]['value'] return self.add_to_cache(name, location, epiweek, value) @functools.lru_cache(maxsize=1) def get_most_recent_issue(self): \"\"\"Return the most recent",
"if available_locations: return tuple(atomic_locations - set(available_locations)) else: # no data is available, assume",
"import secrets from delphi.utils.epidate import EpiDate from delphi.utils.epiweek import add_epiweeks, range_epiweeks from delphi.utils.geo.locations"
] |
[
"providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda:",
"list(provider.traverse()) assert len(all_providers) == 3 assert provider1 in all_providers assert provider2 in all_providers",
"assert len(all_providers) == 2 assert provider1 in all_providers assert provider2 in all_providers def",
"= lambda: \"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch,",
"tests.\"\"\" from dependency_injector import providers def test_traverse(): switch = lambda: \"provider1\" provider1 =",
"= providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) ==",
"= list(provider.traverse()) assert len(all_providers) == 3 assert provider1 in all_providers assert provider2 in",
"== 2 assert provider1 in all_providers assert provider2 in all_providers def test_traverse_switch(): switch",
"lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert",
"list(provider.traverse()) assert len(all_providers) == 2 assert provider1 in all_providers assert provider2 in all_providers",
"list(provider.traverse()) assert len(all_providers) == 3 assert switch in all_providers assert provider1 in all_providers",
"3 assert switch in all_providers assert provider1 in all_providers assert provider2 in all_providers",
"assert provider2 in all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list)",
"== 3 assert switch in all_providers assert provider1 in all_providers assert provider2 in",
"providers def test_traverse(): switch = lambda: \"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict)",
"traversal tests.\"\"\" from dependency_injector import providers def test_traverse(): switch = lambda: \"provider1\" provider1",
") all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert switch in all_providers assert",
"in all_providers assert provider2 in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 =",
"assert len(all_providers) == 3 assert switch in all_providers assert provider1 in all_providers assert",
"all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\",",
"provider2 in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1 =",
"selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1)",
"all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert switch in all_providers assert provider1",
"assert provider1 in all_providers assert provider2 in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list)",
"providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers =",
"from dependency_injector import providers def test_traverse(): switch = lambda: \"provider1\" provider1 = providers.Callable(list)",
"all_providers assert provider2 in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict)",
"len(all_providers) == 2 assert provider1 in all_providers assert provider2 in all_providers def test_traverse_switch():",
"len(all_providers) == 3 assert provider1 in all_providers assert provider2 in all_providers assert selector1",
"providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2, )",
"assert switch in all_providers assert provider1 in all_providers assert provider2 in all_providers def",
"= providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector(",
"= providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers",
"switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector(",
"len(all_providers) == 3 assert switch in all_providers assert provider1 in all_providers assert provider2",
"2 assert provider1 in all_providers assert provider2 in all_providers def test_traverse_switch(): switch =",
"provider traversal tests.\"\"\" from dependency_injector import providers def test_traverse(): switch = lambda: \"provider1\"",
"switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 2 assert provider1",
"provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 2 assert provider1 in all_providers",
"in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda:",
"providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers)",
"provider = providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) ==",
"assert len(all_providers) == 3 assert provider1 in all_providers assert provider2 in all_providers assert",
"\"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse())",
"lambda: \"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1,",
"provider1 in all_providers assert provider2 in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2",
"= providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2,",
"all_providers = list(provider.traverse()) assert len(all_providers) == 2 assert provider1 in all_providers assert provider2",
") provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert provider1 in all_providers",
"provider1 in all_providers assert provider2 in all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\")",
"providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 2 assert",
"in all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 =",
"import providers def test_traverse(): switch = lambda: \"provider1\" provider1 = providers.Callable(list) provider2 =",
") all_providers = list(provider.traverse()) assert len(all_providers) == 2 assert provider1 in all_providers assert",
"dependency_injector import providers def test_traverse(): switch = lambda: \"provider1\" provider1 = providers.Callable(list) provider2",
"provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert",
"all_providers assert provider1 in all_providers assert provider2 in all_providers def test_traverse_overridden(): provider1 =",
"provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider =",
"3 assert provider1 in all_providers assert provider2 in all_providers assert selector1 in all_providers",
"provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert provider1 in all_providers assert",
"providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers =",
"provider2 in all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2",
"= providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch,",
"switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert switch",
"<gh_stars>0 \"\"\"Selector provider traversal tests.\"\"\" from dependency_injector import providers def test_traverse(): switch =",
"assert provider1 in all_providers assert provider2 in all_providers def test_traverse_switch(): switch = providers.Callable(lambda:",
"all_providers assert provider2 in all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 =",
"providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) == 3",
"provider = providers.Selector( lambda: \"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers)",
"test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider =",
"provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert switch in all_providers",
"provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider = providers.Selector( lambda: \"provider2\",",
"\"provider2\", provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert provider1",
"providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1,",
"= providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 3",
"def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider",
"\"\"\"Selector provider traversal tests.\"\"\" from dependency_injector import providers def test_traverse(): switch = lambda:",
"in all_providers assert provider2 in all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1",
"provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 2 assert provider1 in",
"def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1)",
"providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert",
"all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert provider1 in all_providers assert provider2",
"provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse())",
"= providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers",
"test_traverse(): switch = lambda: \"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider =",
"== 3 assert provider1 in all_providers assert provider2 in all_providers assert selector1 in",
"provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert switch in",
"switch = lambda: \"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector(",
"provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2, )",
"provider2=provider2, ) provider.override(selector1) all_providers = list(provider.traverse()) assert len(all_providers) == 3 assert provider1 in",
"\"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2,",
"= providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert",
"= providers.Selector( switch, provider1=provider1, provider2=provider2, ) all_providers = list(provider.traverse()) assert len(all_providers) == 2",
"= list(provider.traverse()) assert len(all_providers) == 2 assert provider1 in all_providers assert provider2 in",
"switch in all_providers assert provider1 in all_providers assert provider2 in all_providers def test_traverse_overridden():",
"def test_traverse(): switch = lambda: \"provider1\" provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider",
"assert provider2 in all_providers def test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1",
"= list(provider.traverse()) assert len(all_providers) == 3 assert switch in all_providers assert provider1 in",
"\"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict) provider = providers.Selector( switch, provider1=provider1, provider2=provider2,",
"test_traverse_overridden(): provider1 = providers.Callable(list) provider2 = providers.Callable(dict) selector1 = providers.Selector(lambda: \"provider1\", provider1=provider1) provider",
"in all_providers assert provider1 in all_providers assert provider2 in all_providers def test_traverse_overridden(): provider1",
"all_providers def test_traverse_switch(): switch = providers.Callable(lambda: \"provider1\") provider1 = providers.Callable(list) provider2 = providers.Callable(dict)"
] |
[
"just a moment ago are all part of the same group. Now, they",
"<-> 6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog for",
"4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 In",
"prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog in direct_conections.keys() if",
"and the other consisting solely of program 1. How many groups are there",
"4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog for prog in direct_conections[id]} toexplore",
"group that contains program ID 0: Program 0 by definition. Program 2, directly",
"to investigate. You walk through the village and record the ID of each",
"4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5",
"small village that is experiencing a little confusion: some programs can't communicate with",
"4, then 2. Program 6 via programs 4, then 2. Therefore, a total",
"groups are there in total? \"\"\" def parse(lines): d = {} for line",
"pass messages between each other until the message reaches the intended recipient. For",
"little confusion: some programs can't communicate with each other. Programs in this village",
"their intended recipient, and the programs suspect that some pipes are missing. They",
"example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the",
"has one or more programs with which it can communicate, and these pipes",
"or more programs with which it can communicate, and these pipes are bidirectional;",
"directly connected to program 0. Program 3 via program 2. Program 4 via",
"bidirectional; if 8 says it can communicate with 11, then 11 will say",
"communicate with each other. Programs in this village communicate using a fixed system",
"lines: l = line.strip() k, v = l.split(' <-> ') d[k] = v.split(',",
"for line in lines: l = line.strip() k, v = l.split(' <-> ')",
"11 will say it can communicate with 8. You need to figure out",
"indirectly. The programs you identified just a moment ago are all part of",
"a little confusion: some programs can't communicate with each other. Programs in this",
"with which it can communicate, and these pipes are bidirectional; if 8 says",
"it can communicate with 11, then 11 will say it can communicate with",
"the total number of groups. In the example above, there were 2 groups:",
"= list(direct_conections.keys()) grouped = set() groups = 0 while ungrouped_progs: prog = ungrouped_progs[0]",
"identified just a moment ago are all part of the same group. Now,",
"all part of the same group. Now, they would like you to determine",
"some of these messages aren't ever reaching their intended recipient, and the programs",
"ID 0. For example, suppose you go door-to-door like a travelling salesman and",
"ones in the group containing program ID 0. The rest of them have",
"ungrouped_progs = [prog for prog in direct_conections.keys() if prog not in grouped] groups",
"between programs using these pipes, but most programs aren't connected to each other",
"--- There are more programs than just the ones in the group containing",
"communicate with 8. You need to figure out how many programs are in",
"them have no way of reaching that group, and still might have no",
"<-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <->",
"d = {} for line in lines: l = line.strip() k, v =",
"For some reason, though, some of these messages aren't ever reaching their intended",
"determine the total number of groups. In the example above, there were 2",
"communicate via pipes either directly or indirectly. The programs you identified just a",
"Program 6 via programs 4, then 2. Therefore, a total of 6 programs",
"def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set() groups = 0 while ungrouped_progs:",
"of groups. In the example above, there were 2 groups: one consisting of",
"def parse(lines): d = {} for line in lines: l = line.strip() k,",
"programs suspect that some pipes are missing. They would like you to investigate.",
"5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog for prog in direct_conections[id]} toexplore =",
"The programs you identified just a moment ago are all part of the",
"can communicate with 8. You need to figure out how many programs are",
"has a pipe that connects it to itself. How many programs are in",
"test_list = \"\"\"0 <-> 2 1 <-> 1 2 <-> 0, 3, 4",
"total? \"\"\" def parse(lines): d = {} for line in lines: l =",
"is experiencing a little confusion: some programs can't communicate with each other. Programs",
"In this example, the following programs are in the group that contains program",
"= {} for line in lines: l = line.strip() k, v = l.split('",
"You walk through the village and record the ID of each program and",
"Plumber --- Walking along the memory banks of the stream, you find a",
"6, then 4, then 2. Program 6 via programs 4, then 2. Therefore,",
"communicate with 11, then 11 will say it can communicate with 8. You",
"find_group(direct_conections, id): connected = {prog for prog in direct_conections[id]} toexplore = connected.copy() explored",
"consisting of programs 0,2,3,4,5,6, and the other consisting solely of program 1. How",
"def test2(): assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ == '__main__':",
"village communicate using a fixed system of pipes. Messages are passed between programs",
"toexplore = connected.copy() explored = set() while toexplore: prog = toexplore.pop() if prog",
"len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped =",
"ID 0? --- Part Two --- There are more programs than just the",
"these messages aren't ever reaching their intended recipient, and the programs suspect that",
"just the ones in the group containing program ID 0. The rest of",
"are all part of the same group. Now, they would like you to",
"test2(): assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ == '__main__': #",
"other consisting solely of program 1. How many groups are there in total?",
"intended recipient, and the programs suspect that some pipes are missing. They would",
"are in the group that contains program ID 0. For example, suppose you",
"5 <-> 6 6 <-> 4, 5 In this example, the following programs",
"then 4, then 2. Program 6 via programs 4, then 2. Therefore, a",
"= toexplore.pop() if prog in explored: continue else: for p in direct_conections[prog]: toexplore.add(p)",
"stream, you find a small village that is experiencing a little confusion: some",
"pipes are bidirectional; if 8 says it can communicate with 11, then 11",
"containing program ID 0. The rest of them have no way of reaching",
"k, v = l.split(' <-> ') d[k] = v.split(', ') return d def",
"continue else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1():",
"part2(): print(count_groups(parse(read()))) if __name__ == '__main__': # test1() # part1() # test2() part2()",
"of these messages aren't ever reaching their intended recipient, and the programs suspect",
"connects it to itself. How many programs are in the group that contains",
"that some pipes are missing. They would like you to investigate. You walk",
"ID of each program and the IDs with which it can communicate directly",
"programs aren't connected to each other directly. Instead, programs pass messages between each",
"0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <->",
"in the group that contains program ID 0: Program 0 by definition. Program",
"programs are in the group that contains program ID 0? --- Part Two",
"the ones in the group containing program ID 0. The rest of them",
"way of reaching each other. A group is a collection of programs that",
"12: Digital Plumber --- Walking along the memory banks of the stream, you",
"parse(lines): d = {} for line in lines: l = line.strip() k, v",
"<-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog for prog in direct_conections[id]}",
"assert 6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs =",
"with 8. You need to figure out how many programs are in the",
"other until the message reaches the intended recipient. For some reason, though, some",
"--- Walking along the memory banks of the stream, you find a small",
"6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys())",
"group; all but program 1, which has a pipe that connects it to",
"return groups def test2(): assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__",
"most programs aren't connected to each other directly. Instead, programs pass messages between",
"programs with which it can communicate, and these pipes are bidirectional; if 8",
"investigate. You walk through the village and record the ID of each program",
"0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog",
"some reason, though, some of these messages aren't ever reaching their intended recipient,",
"would like you to investigate. You walk through the village and record the",
"') d[k] = v.split(', ') return d def read(): with open('inputs/day12.txt') as fd:",
"connected.copy() explored = set() while toexplore: prog = toexplore.pop() if prog in explored:",
"which it can communicate directly (your puzzle input). Each program has one or",
"0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5",
"of programs that can all communicate via pipes either directly or indirectly. The",
"suppose you go door-to-door like a travelling salesman and record the following list:",
"go door-to-door like a travelling salesman and record the following list: 0 <->",
"program 1. How many groups are there in total? \"\"\" def parse(lines): d",
"connected to each other directly. Instead, programs pass messages between each other until",
"toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1(): assert 6 == len(find_group(parse(test_list), '0')) def",
"pipes. Messages are passed between programs using these pipes, but most programs aren't",
"11, then 11 will say it can communicate with 8. You need to",
"you identified just a moment ago are all part of the same group.",
"return connected def test1(): assert 6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0')))",
"2. Program 5 via programs 6, then 4, then 2. Program 6 via",
"4, 5 In this example, the following programs are in the group that",
"\"\"\" --- Day 12: Digital Plumber --- Walking along the memory banks of",
"pipe that connects it to itself. How many programs are in the group",
"Walking along the memory banks of the stream, you find a small village",
"prog)) ungrouped_progs = [prog for prog in direct_conections.keys() if prog not in grouped]",
"in this group; all but program 1, which has a pipe that connects",
"in this village communicate using a fixed system of pipes. Messages are passed",
"then 2. Therefore, a total of 6 programs are in this group; all",
"groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely of program",
"this group; all but program 1, which has a pipe that connects it",
"there in total? \"\"\" def parse(lines): d = {} for line in lines:",
"is a collection of programs that can all communicate via pipes either directly",
"ever reaching their intended recipient, and the programs suspect that some pipes are",
"1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4",
"might have no way of reaching each other. A group is a collection",
"each program and the IDs with which it can communicate directly (your puzzle",
"ungrouped_progs = list(direct_conections.keys()) grouped = set() groups = 0 while ungrouped_progs: prog =",
"through the village and record the ID of each program and the IDs",
"explored.add(prog) return connected def test1(): assert 6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()),",
"a collection of programs that can all communicate via pipes either directly or",
"2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3,",
"prog in direct_conections.keys() if prog not in grouped] groups += 1 return groups",
"group containing program ID 0. The rest of them have no way of",
"6 5 <-> 6 6 <-> 4, 5 In this example, the following",
"the intended recipient. For some reason, though, some of these messages aren't ever",
"group that contains program ID 0. For example, suppose you go door-to-door like",
"read(): with open('inputs/day12.txt') as fd: return fd.readlines() test_list = \"\"\"0 <-> 2 1",
"(your puzzle input). Each program has one or more programs with which it",
"else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1(): assert",
"a fixed system of pipes. Messages are passed between programs using these pipes,",
"no way of reaching that group, and still might have no way of",
"connected def test1(): assert 6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def",
"to program 0. Program 3 via program 2. Program 4 via program 2.",
"in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1(): assert 6 == len(find_group(parse(test_list),",
"that contains program ID 0. For example, suppose you go door-to-door like a",
"it can communicate directly (your puzzle input). Each program has one or more",
"can communicate with 11, then 11 will say it can communicate with 8.",
"that contains program ID 0: Program 0 by definition. Program 2, directly connected",
"2. Program 6 via programs 4, then 2. Therefore, a total of 6",
"the group that contains program ID 0. For example, suppose you go door-to-door",
"via programs 6, then 4, then 2. Program 6 via programs 4, then",
"<gh_stars>0 \"\"\" --- Day 12: Digital Plumber --- Walking along the memory banks",
"contains program ID 0: Program 0 by definition. Program 2, directly connected to",
"of programs 0,2,3,4,5,6, and the other consisting solely of program 1. How many",
"in the group that contains program ID 0? --- Part Two --- There",
"= set() while toexplore: prog = toexplore.pop() if prog in explored: continue else:",
"are in the group that contains program ID 0? --- Part Two ---",
"a pipe that connects it to itself. How many programs are in the",
"with open('inputs/day12.txt') as fd: return fd.readlines() test_list = \"\"\"0 <-> 2 1 <->",
"return fd.readlines() test_list = \"\"\"0 <-> 2 1 <-> 1 2 <-> 0,",
"in explored: continue else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected",
"def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set() groups",
"in direct_conections[id]} toexplore = connected.copy() explored = set() while toexplore: prog = toexplore.pop()",
"explored: continue else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def",
"moment ago are all part of the same group. Now, they would like",
"3 via program 2. Program 4 via program 2. Program 5 via programs",
"0? --- Part Two --- There are more programs than just the ones",
"Digital Plumber --- Walking along the memory banks of the stream, you find",
"to each other directly. Instead, programs pass messages between each other until the",
"= l.split(' <-> ') d[k] = v.split(', ') return d def read(): with",
"You need to figure out how many programs are in the group that",
"each other. A group is a collection of programs that can all communicate",
"it can communicate with 8. You need to figure out how many programs",
"it can communicate, and these pipes are bidirectional; if 8 says it can",
"program ID 0. For example, suppose you go door-to-door like a travelling salesman",
"<-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 In this",
"while toexplore: prog = toexplore.pop() if prog in explored: continue else: for p",
"reaching their intended recipient, and the programs suspect that some pipes are missing.",
"contains program ID 0. For example, suppose you go door-to-door like a travelling",
"of reaching each other. A group is a collection of programs that can",
"Messages are passed between programs using these pipes, but most programs aren't connected",
"Programs in this village communicate using a fixed system of pipes. Messages are",
"you to determine the total number of groups. In the example above, there",
"reason, though, some of these messages aren't ever reaching their intended recipient, and",
"the IDs with which it can communicate directly (your puzzle input). Each program",
"programs can't communicate with each other. Programs in this village communicate using a",
"4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6",
"2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4,",
"3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <->",
"one or more programs with which it can communicate, and these pipes are",
"in grouped] groups += 1 return groups def test2(): assert 2 == count_groups(parse(test_list))",
"or indirectly. The programs you identified just a moment ago are all part",
"1 return groups def test2(): assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if",
"{} for line in lines: l = line.strip() k, v = l.split(' <->",
"program 2. Program 4 via program 2. Program 5 via programs 6, then",
"for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1(): assert 6",
"explored = set() while toexplore: prog = toexplore.pop() if prog in explored: continue",
"= v.split(', ') return d def read(): with open('inputs/day12.txt') as fd: return fd.readlines()",
"part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set() groups =",
"Part Two --- There are more programs than just the ones in the",
"walk through the village and record the ID of each program and the",
"the following programs are in the group that contains program ID 0: Program",
"Program 4 via program 2. Program 5 via programs 6, then 4, then",
"village and record the ID of each program and the IDs with which",
"in the group that contains program ID 0. For example, suppose you go",
"like a travelling salesman and record the following list: 0 <-> 2 1",
"using these pipes, but most programs aren't connected to each other directly. Instead,",
"== len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped",
"to determine the total number of groups. In the example above, there were",
"fd: return fd.readlines() test_list = \"\"\"0 <-> 2 1 <-> 1 2 <->",
"pipes are missing. They would like you to investigate. You walk through the",
"return d def read(): with open('inputs/day12.txt') as fd: return fd.readlines() test_list = \"\"\"0",
"connected = {prog for prog in direct_conections[id]} toexplore = connected.copy() explored = set()",
"def read(): with open('inputs/day12.txt') as fd: return fd.readlines() test_list = \"\"\"0 <-> 2",
"direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1(): assert 6 == len(find_group(parse(test_list), '0'))",
"1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2,",
"were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely",
"groups += 1 return groups def test2(): assert 2 == count_groups(parse(test_list)) def part2():",
"and the IDs with which it can communicate directly (your puzzle input). Each",
"= {prog for prog in direct_conections[id]} toexplore = connected.copy() explored = set() while",
"with which it can communicate directly (your puzzle input). Each program has one",
"for prog in direct_conections[id]} toexplore = connected.copy() explored = set() while toexplore: prog",
"prog in explored: continue else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return",
"program ID 0? --- Part Two --- There are more programs than just",
"ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog in direct_conections.keys()",
"Now, they would like you to determine the total number of groups. In",
"via program 2. Program 5 via programs 6, then 4, then 2. Program",
"the village and record the ID of each program and the IDs with",
"communicate, and these pipes are bidirectional; if 8 says it can communicate with",
"group. Now, they would like you to determine the total number of groups.",
"in total? \"\"\" def parse(lines): d = {} for line in lines: l",
"input). Each program has one or more programs with which it can communicate,",
"Each program has one or more programs with which it can communicate, and",
"the same group. Now, they would like you to determine the total number",
"list: 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3",
"that group, and still might have no way of reaching each other. A",
"directly. Instead, programs pass messages between each other until the message reaches the",
"are bidirectional; if 8 says it can communicate with 11, then 11 will",
"that connects it to itself. How many programs are in the group that",
"of 6 programs are in this group; all but program 1, which has",
"these pipes are bidirectional; if 8 says it can communicate with 11, then",
"of pipes. Messages are passed between programs using these pipes, but most programs",
"[prog for prog in direct_conections.keys() if prog not in grouped] groups += 1",
"can communicate, and these pipes are bidirectional; if 8 says it can communicate",
"the memory banks of the stream, you find a small village that is",
"are there in total? \"\"\" def parse(lines): d = {} for line in",
"1. How many groups are there in total? \"\"\" def parse(lines): d =",
"def find_group(direct_conections, id): connected = {prog for prog in direct_conections[id]} toexplore = connected.copy()",
"programs 6, then 4, then 2. Program 6 via programs 4, then 2.",
"d def read(): with open('inputs/day12.txt') as fd: return fd.readlines() test_list = \"\"\"0 <->",
"if prog not in grouped] groups += 1 return groups def test2(): assert",
"def part2(): print(count_groups(parse(read()))) if __name__ == '__main__': # test1() # part1() # test2()",
"that can all communicate via pipes either directly or indirectly. The programs you",
"5 In this example, the following programs are in the group that contains",
"can communicate directly (your puzzle input). Each program has one or more programs",
"open('inputs/day12.txt') as fd: return fd.readlines() test_list = \"\"\"0 <-> 2 1 <-> 1",
"0 by definition. Program 2, directly connected to program 0. Program 3 via",
"if prog in explored: continue else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog)",
"<-> 4, 5 In this example, the following programs are in the group",
"that is experiencing a little confusion: some programs can't communicate with each other.",
"are in this group; all but program 1, which has a pipe that",
"group that contains program ID 0? --- Part Two --- There are more",
"can't communicate with each other. Programs in this village communicate using a fixed",
"program 1, which has a pipe that connects it to itself. How many",
"program has one or more programs with which it can communicate, and these",
"more programs than just the ones in the group containing program ID 0.",
"and record the following list: 0 <-> 2 1 <-> 1 2 <->",
"this example, the following programs are in the group that contains program ID",
"connected to program 0. Program 3 via program 2. Program 4 via program",
"0. The rest of them have no way of reaching that group, and",
"you go door-to-door like a travelling salesman and record the following list: 0",
"Program 5 via programs 6, then 4, then 2. Program 6 via programs",
"via program 2. Program 4 via program 2. Program 5 via programs 6,",
"more programs with which it can communicate, and these pipes are bidirectional; if",
"recipient. For some reason, though, some of these messages aren't ever reaching their",
"puzzle input). Each program has one or more programs with which it can",
"6 <-> 4, 5 In this example, the following programs are in the",
"the other consisting solely of program 1. How many groups are there in",
"the stream, you find a small village that is experiencing a little confusion:",
"programs pass messages between each other until the message reaches the intended recipient.",
"will say it can communicate with 8. You need to figure out how",
"of program 1. How many groups are there in total? \"\"\" def parse(lines):",
"4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5\"\"\".split('\\n') def",
"programs than just the ones in the group containing program ID 0. The",
"for prog in direct_conections.keys() if prog not in grouped] groups += 1 return",
"are in the group that contains program ID 0: Program 0 by definition.",
"Program 3 via program 2. Program 4 via program 2. Program 5 via",
"reaching that group, and still might have no way of reaching each other.",
"count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ == '__main__': # test1() # part1() #",
"reaching each other. A group is a collection of programs that can all",
"travelling salesman and record the following list: 0 <-> 2 1 <-> 1",
"programs you identified just a moment ago are all part of the same",
"direct_conections.keys() if prog not in grouped] groups += 1 return groups def test2():",
"program ID 0. The rest of them have no way of reaching that",
"grouped] groups += 1 return groups def test2(): assert 2 == count_groups(parse(test_list)) def",
"how many programs are in the group that contains program ID 0. For",
"There are more programs than just the ones in the group containing program",
"line.strip() k, v = l.split(' <-> ') d[k] = v.split(', ') return d",
"set() groups = 0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs =",
"3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6",
"each other. Programs in this village communicate using a fixed system of pipes.",
"of reaching that group, and still might have no way of reaching each",
"print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set() groups = 0",
"1, which has a pipe that connects it to itself. How many programs",
"with 11, then 11 will say it can communicate with 8. You need",
"the group that contains program ID 0? --- Part Two --- There are",
"2, 3, 6 5 <-> 6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id):",
"8. You need to figure out how many programs are in the group",
"Two --- There are more programs than just the ones in the group",
"following list: 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4",
"you find a small village that is experiencing a little confusion: some programs",
"directly (your puzzle input). Each program has one or more programs with which",
"message reaches the intended recipient. For some reason, though, some of these messages",
"0. Program 3 via program 2. Program 4 via program 2. Program 5",
"communicate directly (your puzzle input). Each program has one or more programs with",
"programs are in the group that contains program ID 0: Program 0 by",
"all but program 1, which has a pipe that connects it to itself.",
"many programs are in the group that contains program ID 0. For example,",
"of each program and the IDs with which it can communicate directly (your",
"def test1(): assert 6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections):",
"= set() groups = 0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs",
"2, 3, 6 5 <-> 6 6 <-> 4, 5 In this example,",
"communicate using a fixed system of pipes. Messages are passed between programs using",
"reaches the intended recipient. For some reason, though, some of these messages aren't",
"connected.add(p) explored.add(prog) return connected def test1(): assert 6 == len(find_group(parse(test_list), '0')) def part1():",
"5 via programs 6, then 4, then 2. Program 6 via programs 4,",
"in lines: l = line.strip() k, v = l.split(' <-> ') d[k] =",
"have no way of reaching each other. A group is a collection of",
"= connected.copy() explored = set() while toexplore: prog = toexplore.pop() if prog in",
"prog in direct_conections[id]} toexplore = connected.copy() explored = set() while toexplore: prog =",
"the programs suspect that some pipes are missing. They would like you to",
"--- Day 12: Digital Plumber --- Walking along the memory banks of the",
"directly or indirectly. The programs you identified just a moment ago are all",
"like you to investigate. You walk through the village and record the ID",
"example, suppose you go door-to-door like a travelling salesman and record the following",
"via programs 4, then 2. Therefore, a total of 6 programs are in",
"you to investigate. You walk through the village and record the ID of",
"messages aren't ever reaching their intended recipient, and the programs suspect that some",
"l = line.strip() k, v = l.split(' <-> ') d[k] = v.split(', ')",
"'0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set() groups = 0 while",
"though, some of these messages aren't ever reaching their intended recipient, and the",
"Program 0 by definition. Program 2, directly connected to program 0. Program 3",
"a small village that is experiencing a little confusion: some programs can't communicate",
"programs are in the group that contains program ID 0. For example, suppose",
"For example, suppose you go door-to-door like a travelling salesman and record the",
"group is a collection of programs that can all communicate via pipes either",
"a travelling salesman and record the following list: 0 <-> 2 1 <->",
"record the following list: 0 <-> 2 1 <-> 1 2 <-> 0,",
"2. Program 4 via program 2. Program 5 via programs 6, then 4,",
"2. Therefore, a total of 6 programs are in this group; all but",
"by definition. Program 2, directly connected to program 0. Program 3 via program",
"programs that can all communicate via pipes either directly or indirectly. The programs",
"say it can communicate with 8. You need to figure out how many",
"\"\"\"0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <->",
"says it can communicate with 11, then 11 will say it can communicate",
"experiencing a little confusion: some programs can't communicate with each other. Programs in",
"2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely of",
"contains program ID 0? --- Part Two --- There are more programs than",
"<-> 6 6 <-> 4, 5 In this example, the following programs are",
"6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog for prog",
"are missing. They would like you to investigate. You walk through the village",
"== count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ == '__main__': # test1() # part1()",
"itself. How many programs are in the group that contains program ID 0?",
"find a small village that is experiencing a little confusion: some programs can't",
"many programs are in the group that contains program ID 0? --- Part",
"recipient, and the programs suspect that some pipes are missing. They would like",
"intended recipient. For some reason, though, some of these messages aren't ever reaching",
"confusion: some programs can't communicate with each other. Programs in this village communicate",
"door-to-door like a travelling salesman and record the following list: 0 <-> 2",
"= \"\"\"0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3",
"the ID of each program and the IDs with which it can communicate",
"would like you to determine the total number of groups. In the example",
"= 0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for",
"aren't connected to each other directly. Instead, programs pass messages between each other",
"no way of reaching each other. A group is a collection of programs",
"program and the IDs with which it can communicate directly (your puzzle input).",
"have no way of reaching that group, and still might have no way",
"other. Programs in this village communicate using a fixed system of pipes. Messages",
"programs using these pipes, but most programs aren't connected to each other directly.",
"record the ID of each program and the IDs with which it can",
"3, 6 5 <-> 6 6 <-> 4, 5 In this example, the",
"ID 0: Program 0 by definition. Program 2, directly connected to program 0.",
"v = l.split(' <-> ') d[k] = v.split(', ') return d def read():",
"village that is experiencing a little confusion: some programs can't communicate with each",
"some pipes are missing. They would like you to investigate. You walk through",
"example, the following programs are in the group that contains program ID 0:",
"program 0. Program 3 via program 2. Program 4 via program 2. Program",
"0: Program 0 by definition. Program 2, directly connected to program 0. Program",
"system of pipes. Messages are passed between programs using these pipes, but most",
"In the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6,",
"can all communicate via pipes either directly or indirectly. The programs you identified",
"\"\"\" def parse(lines): d = {} for line in lines: l = line.strip()",
"they would like you to determine the total number of groups. In the",
"total number of groups. In the example above, there were 2 groups: one",
"Therefore, a total of 6 programs are in this group; all but program",
"are passed between programs using these pipes, but most programs aren't connected to",
"d[k] = v.split(', ') return d def read(): with open('inputs/day12.txt') as fd: return",
"grouped = set() groups = 0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog))",
"ago are all part of the same group. Now, they would like you",
"p in direct_conections[prog]: toexplore.add(p) connected.add(p) explored.add(prog) return connected def test1(): assert 6 ==",
"consisting solely of program 1. How many groups are there in total? \"\"\"",
"along the memory banks of the stream, you find a small village that",
"the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and",
"v.split(', ') return d def read(): with open('inputs/day12.txt') as fd: return fd.readlines() test_list",
"the group that contains program ID 0: Program 0 by definition. Program 2,",
"are more programs than just the ones in the group containing program ID",
"6 5 <-> 6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected =",
"groups def test2(): assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ ==",
"this village communicate using a fixed system of pipes. Messages are passed between",
"4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5\"\"\".split('\\n')",
"id): connected = {prog for prog in direct_conections[id]} toexplore = connected.copy() explored =",
"--- Part Two --- There are more programs than just the ones in",
"memory banks of the stream, you find a small village that is experiencing",
"while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog in",
"the message reaches the intended recipient. For some reason, though, some of these",
"8 says it can communicate with 11, then 11 will say it can",
"than just the ones in the group containing program ID 0. The rest",
"How many programs are in the group that contains program ID 0? ---",
"a total of 6 programs are in this group; all but program 1,",
"many groups are there in total? \"\"\" def parse(lines): d = {} for",
"pipes, but most programs aren't connected to each other directly. Instead, programs pass",
"grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog in direct_conections.keys() if prog not in",
"but program 1, which has a pipe that connects it to itself. How",
"assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ == '__main__': # test1()",
"way of reaching that group, and still might have no way of reaching",
"6 via programs 4, then 2. Therefore, a total of 6 programs are",
"need to figure out how many programs are in the group that contains",
"then 2. Program 6 via programs 4, then 2. Therefore, a total of",
"there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting",
"banks of the stream, you find a small village that is experiencing a",
"some programs can't communicate with each other. Programs in this village communicate using",
"and the programs suspect that some pipes are missing. They would like you",
"figure out how many programs are in the group that contains program ID",
"2, directly connected to program 0. Program 3 via program 2. Program 4",
"using a fixed system of pipes. Messages are passed between programs using these",
"Day 12: Digital Plumber --- Walking along the memory banks of the stream,",
"following programs are in the group that contains program ID 0: Program 0",
"and still might have no way of reaching each other. A group is",
"of the same group. Now, they would like you to determine the total",
"aren't ever reaching their intended recipient, and the programs suspect that some pipes",
"then 11 will say it can communicate with 8. You need to figure",
"6 6 <-> 4, 5 In this example, the following programs are in",
"line in lines: l = line.strip() k, v = l.split(' <-> ') d[k]",
"set() while toexplore: prog = toexplore.pop() if prog in explored: continue else: for",
"and record the ID of each program and the IDs with which it",
"it to itself. How many programs are in the group that contains program",
"<-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6",
"{prog for prog in direct_conections[id]} toexplore = connected.copy() explored = set() while toexplore:",
"missing. They would like you to investigate. You walk through the village and",
"IDs with which it can communicate directly (your puzzle input). Each program has",
"in the group containing program ID 0. The rest of them have no",
"<-> 2, 3, 6 5 <-> 6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections,",
"Instead, programs pass messages between each other until the message reaches the intended",
"programs 4, then 2. Therefore, a total of 6 programs are in this",
"passed between programs using these pipes, but most programs aren't connected to each",
"to figure out how many programs are in the group that contains program",
"6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog for prog in",
"The rest of them have no way of reaching that group, and still",
"= line.strip() k, v = l.split(' <-> ') d[k] = v.split(', ') return",
"+= 1 return groups def test2(): assert 2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read())))",
"a moment ago are all part of the same group. Now, they would",
"<-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2,",
"<-> ') d[k] = v.split(', ') return d def read(): with open('inputs/day12.txt') as",
"prog = toexplore.pop() if prog in explored: continue else: for p in direct_conections[prog]:",
"2 == count_groups(parse(test_list)) def part2(): print(count_groups(parse(read()))) if __name__ == '__main__': # test1() #",
"definition. Program 2, directly connected to program 0. Program 3 via program 2.",
"programs are in this group; all but program 1, which has a pipe",
"group, and still might have no way of reaching each other. A group",
"with each other. Programs in this village communicate using a fixed system of",
"direct_conections[id]} toexplore = connected.copy() explored = set() while toexplore: prog = toexplore.pop() if",
"between each other until the message reaches the intended recipient. For some reason,",
"either directly or indirectly. The programs you identified just a moment ago are",
"6 programs are in this group; all but program 1, which has a",
"fixed system of pipes. Messages are passed between programs using these pipes, but",
"rest of them have no way of reaching that group, and still might",
"these pipes, but most programs aren't connected to each other directly. Instead, programs",
"They would like you to investigate. You walk through the village and record",
"<-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <->",
"like you to determine the total number of groups. In the example above,",
"that contains program ID 0? --- Part Two --- There are more programs",
"and these pipes are bidirectional; if 8 says it can communicate with 11,",
"program ID 0: Program 0 by definition. Program 2, directly connected to program",
"program 2. Program 5 via programs 6, then 4, then 2. Program 6",
"number of groups. In the example above, there were 2 groups: one consisting",
"count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set() groups = 0 while ungrouped_progs: prog",
"4, then 2. Therefore, a total of 6 programs are in this group;",
"as fd: return fd.readlines() test_list = \"\"\"0 <-> 2 1 <-> 1 2",
"ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog in direct_conections.keys() if prog not",
"above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other",
"A group is a collection of programs that can all communicate via pipes",
"which has a pipe that connects it to itself. How many programs are",
"groups. In the example above, there were 2 groups: one consisting of programs",
"of the stream, you find a small village that is experiencing a little",
"programs 0,2,3,4,5,6, and the other consisting solely of program 1. How many groups",
"'0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs = list(direct_conections.keys()) grouped = set()",
"4 via program 2. Program 5 via programs 6, then 4, then 2.",
"one consisting of programs 0,2,3,4,5,6, and the other consisting solely of program 1.",
"list(direct_conections.keys()) grouped = set() groups = 0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections,",
"prog not in grouped] groups += 1 return groups def test2(): assert 2",
"same group. Now, they would like you to determine the total number of",
"other. A group is a collection of programs that can all communicate via",
"via pipes either directly or indirectly. The programs you identified just a moment",
"toexplore: prog = toexplore.pop() if prog in explored: continue else: for p in",
"test1(): assert 6 == len(find_group(parse(test_list), '0')) def part1(): print(len(find_group(parse(read()), '0'))) def count_groups(direct_conections): ungrouped_progs",
"of them have no way of reaching that group, and still might have",
"to itself. How many programs are in the group that contains program ID",
"all communicate via pipes either directly or indirectly. The programs you identified just",
"Program 2, directly connected to program 0. Program 3 via program 2. Program",
"= ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog for prog in direct_conections.keys() if prog",
"collection of programs that can all communicate via pipes either directly or indirectly.",
"part of the same group. Now, they would like you to determine the",
"pipes either directly or indirectly. The programs you identified just a moment ago",
"each other directly. Instead, programs pass messages between each other until the message",
"but most programs aren't connected to each other directly. Instead, programs pass messages",
"ID 0. The rest of them have no way of reaching that group,",
"total of 6 programs are in this group; all but program 1, which",
"out how many programs are in the group that contains program ID 0.",
"the following list: 0 <-> 2 1 <-> 1 2 <-> 0, 3,",
"if 8 says it can communicate with 11, then 11 will say it",
"not in grouped] groups += 1 return groups def test2(): assert 2 ==",
"l.split(' <-> ') d[k] = v.split(', ') return d def read(): with open('inputs/day12.txt')",
"fd.readlines() test_list = \"\"\"0 <-> 2 1 <-> 1 2 <-> 0, 3,",
"0. For example, suppose you go door-to-door like a travelling salesman and record",
"0,2,3,4,5,6, and the other consisting solely of program 1. How many groups are",
"5 <-> 6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected = {prog",
"messages between each other until the message reaches the intended recipient. For some",
"in direct_conections.keys() if prog not in grouped] groups += 1 return groups def",
"') return d def read(): with open('inputs/day12.txt') as fd: return fd.readlines() test_list =",
"2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4",
"groups = 0 while ungrouped_progs: prog = ungrouped_progs[0] grouped.update(find_group(direct_conections, prog)) ungrouped_progs = [prog",
"= [prog for prog in direct_conections.keys() if prog not in grouped] groups +=",
"3, 6 5 <-> 6 6 <-> 4, 5\"\"\".split('\\n') def find_group(direct_conections, id): connected",
"the group containing program ID 0. The rest of them have no way",
"other directly. Instead, programs pass messages between each other until the message reaches",
"still might have no way of reaching each other. A group is a",
"suspect that some pipes are missing. They would like you to investigate. You",
"solely of program 1. How many groups are there in total? \"\"\" def",
"which it can communicate, and these pipes are bidirectional; if 8 says it",
"each other until the message reaches the intended recipient. For some reason, though,",
"until the message reaches the intended recipient. For some reason, though, some of",
"toexplore.pop() if prog in explored: continue else: for p in direct_conections[prog]: toexplore.add(p) connected.add(p)",
"How many groups are there in total? \"\"\" def parse(lines): d = {}",
"salesman and record the following list: 0 <-> 2 1 <-> 1 2"
] |
[
".models import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False)",
"sender, } return Message.objects.create(**response_data) class Meta: model = Message fields = [ 'message_id',",
"= User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content': content, 'recipient': recipient, 'sender': sender,",
"serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True)",
"= serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title =",
"serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title'] content = validated_data['content']",
"create(self, validated_data): title = validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient =",
"'content': content, 'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data) class Meta: model =",
"import User from rest_framework import serializers from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id",
"= serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField() timestamp =",
"sender = serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title",
"serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender']))",
"= { 'title': title, 'content': content, 'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data)",
"= serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title'] content = validated_data['content'] sender =",
"MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content = serializers.CharField() sender",
"title = validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data",
"title, 'content': content, 'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data) class Meta: model",
"User from rest_framework import serializers from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id =",
"model = Message fields = [ 'message_id', 'title', 'content', 'sender', 'recipient', 'timestamp' ]",
"read_only=True, required=False) title = serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField() recipient =",
"serializers from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title",
"from rest_framework import serializers from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id',",
"= validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title': title,",
"recipient, 'sender': sender, } return Message.objects.create(**response_data) class Meta: model = Message fields =",
"from django.contrib.auth.models import User from rest_framework import serializers from .models import Message class",
"message_id = serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content = serializers.CharField() sender =",
"= serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField()",
"validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content':",
"title = serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField() timestamp",
"= validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data =",
"class Meta: model = Message fields = [ 'message_id', 'title', 'content', 'sender', 'recipient',",
"return Message.objects.create(**response_data) class Meta: model = Message fields = [ 'message_id', 'title', 'content',",
"User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content': content, 'recipient': recipient,",
"recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title'] content",
"{ 'title': title, 'content': content, 'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data) class",
"recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content': content, 'recipient': recipient, 'sender':",
"django.contrib.auth.models import User from rest_framework import serializers from .models import Message class MessageSerializer(serializers.ModelSerializer):",
"class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content = serializers.CharField()",
"validated_data): title = validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient'])",
"content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title':",
"'title': title, 'content': content, 'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data) class Meta:",
"Message.objects.create(**response_data) class Meta: model = Message fields = [ 'message_id', 'title', 'content', 'sender',",
"import serializers from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False)",
"rest_framework import serializers from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True,",
"'sender': sender, } return Message.objects.create(**response_data) class Meta: model = Message fields = [",
"= User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content': content, 'recipient':",
"from .models import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title =",
"Meta: model = Message fields = [ 'message_id', 'title', 'content', 'sender', 'recipient', 'timestamp'",
"def create(self, validated_data): title = validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient",
"= serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self,",
"content = serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def",
"serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField() recipient",
"response_data = { 'title': title, 'content': content, 'recipient': recipient, 'sender': sender, } return",
"timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title'] content = validated_data['content'] sender",
"serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data):",
"User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content': content, 'recipient': recipient, 'sender': sender, }",
"'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data) class Meta: model = Message fields",
"<reponame>jpaul121/Banter from django.contrib.auth.models import User from rest_framework import serializers from .models import Message",
"Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content =",
"validated_data['title'] content = validated_data['content'] sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = {",
"import Message class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SlugField(source='id', read_only=True, required=False) title = serializers.CharField(required=False) content",
"sender = User.objects.get(id=int(validated_data['sender'])) recipient = User.objects.get(username=validated_data['recipient']) response_data = { 'title': title, 'content': content,",
"content, 'recipient': recipient, 'sender': sender, } return Message.objects.create(**response_data) class Meta: model = Message",
"= serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title'] content =",
"serializers.SlugField() recipient = serializers.SlugField() timestamp = serializers.DateTimeField(read_only=True) def create(self, validated_data): title = validated_data['title']",
"} return Message.objects.create(**response_data) class Meta: model = Message fields = [ 'message_id', 'title',",
"required=False) title = serializers.CharField(required=False) content = serializers.CharField() sender = serializers.SlugField() recipient = serializers.SlugField()"
] |
[
"except OSError: return True def get_usable_port(): port = 39000 while is_port_in_use(port): # check",
"path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed to run on",
"elif sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well'",
"path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ:",
"logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:",
"to stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter)",
"not yet exist if not path.exists(): path.mkdir(parents=True) # path exists, but is a",
"not path.exists(): path.mkdir(parents=True) # path exists, but is a file if not path.is_dir():",
"except (URLError, HTTPError): port += 1 if port == 39010: show_error('No suitable port",
"else: show_error('Wishing Well is only designed to run on Windows or Linux based",
"on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well",
"timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on port %d.",
"= logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port):",
"frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window window_width",
"return path def get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot find the log",
"= root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2), int(screen_height / 2 -",
"urlopen from urllib.error import URLError, HTTPError from .exceptions import LogNotFoundError def get_data_path(): if",
"is a file if not path.is_dir(): show_error(f'{path} already exists, but is a file.')",
"/ 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in",
"import os import socket import sys import tkinter import webbrowser from pathlib import",
"wishing well is already running on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as",
"pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on port %d. Quitting', port) sys.exit(1)",
"'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ:",
"from pathlib import Path from tkinter import ttk from urllib.request import urlopen from",
"import sys import tkinter import webbrowser from pathlib import Path from tkinter import",
"'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) /",
"= root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width",
"sys.argv[1] == '--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'),",
"LogNotFoundError('Cannot find the log file on non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin",
"path.exists(): path.mkdir(parents=True) # path exists, but is a file if not path.is_dir(): show_error(f'{path}",
")) return False except OSError: return True def get_usable_port(): port = 39000 while",
"root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2), int(screen_height / 2 - window_height",
"logging import os import socket import sys import tkinter import webbrowser from pathlib",
"but is a file if not path.is_dir(): show_error(f'{path} already exists, but is a",
"only designed to run on Windows or Linux based systems.') # create dir",
"Impact/output_log.txt' if not path.exists(): return None return path def set_up_logging(): log_level = logging.DEBUG",
"1 and sys.argv[1] == '--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path()",
"/ 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay',",
"39000 while is_port_in_use(port): # check if wishing well is already running on this",
"port )) return False except OSError: return True def get_usable_port(): port = 39000",
"def get_usable_port(): port = 39000 while is_port_in_use(port): # check if wishing well is",
"logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add a stream handler for log output",
"path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin':",
"is already running on port %d. Quitting', port) sys.exit(1) except (URLError, HTTPError): port",
"'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed to",
"the window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height =",
"= Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ: path",
"raise LogNotFoundError('Cannot find the log file on non-Windows systems.') path = Path(os.environ['USERPROFILE']) /",
".exceptions import LogNotFoundError def get_data_path(): if sys.platform == 'win32': path = Path(os.environ['APPDATA']) /",
"exists, but is a file if not path.is_dir(): show_error(f'{path} already exists, but is",
"OSError: return True def get_usable_port(): port = 39000 while is_port_in_use(port): # check if",
"logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) /",
"Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed to run on Windows or",
"import URLError, HTTPError from .exceptions import LogNotFoundError def get_data_path(): if sys.platform == 'win32':",
"already running on port %d. Quitting', port) sys.exit(1) except (URLError, HTTPError): port +=",
"from tkinter import ttk from urllib.request import urlopen from urllib.error import URLError, HTTPError",
"'darwin': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path =",
"dir if it does not yet exist if not path.exists(): path.mkdir(parents=True) # path",
"HTTPError): port += 1 if port == 39010: show_error('No suitable port found.') return",
"/ 2 - window_width / 2), int(screen_height / 2 - window_height / 2)))",
"find the log file on non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt'",
"root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting",
"- window_width / 2), int(screen_height / 2 - window_height / 2))) root.mainloop() logging.info('Quitting')",
"socket import sys import tkinter import webbrowser from pathlib import Path from tkinter",
"/ 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed",
"root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack()",
"2 - window_width / 2), int(screen_height / 2 - window_height / 2))) root.mainloop()",
"= 39000 while is_port_in_use(port): # check if wishing well is already running on",
"ttk from urllib.request import urlopen from urllib.error import URLError, HTTPError from .exceptions import",
"Quitting', port) sys.exit(1) except (URLError, HTTPError): port += 1 if port == 39010:",
"ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window window_width = root.winfo_reqwidth() window_height",
"not path.exists(): return None return path def set_up_logging(): log_level = logging.DEBUG if len(sys.argv)",
"False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame,",
"else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed to run",
"but is a file.') return path def get_log_path(): if sys.platform != 'win32': raise",
"port found.') return port def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300,",
"'wishing-well.log'), format=log_format, level=log_level) # add a stream handler for log output to stdout",
"get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot find the log file on non-Windows",
"import Path from tkinter import ttk from urllib.request import urlopen from urllib.error import",
"_: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on port %d. Quitting', port)",
"a file.') return path def get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot find",
"add a stream handler for log output to stdout root_logger = logging.getLogger() stdout_handler",
"non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None",
"level=log_level) # add a stream handler for log output to stdout root_logger =",
"root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack()",
"try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running",
"= tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame",
"the log file on non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if",
"!= 'win32': raise LogNotFoundError('Cannot find the log file on non-Windows systems.') path =",
"path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None return path",
"== 39010: show_error('No suitable port found.') return port def show_error(message): logging.error(message) root =",
"else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ: path",
"log output to stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter =",
"not path.is_dir(): show_error(f'{path} already exists, but is a file.') return path def get_log_path():",
"log_level = logging.DEBUG if len(sys.argv) > 1 and sys.argv[1] == '--debug' else logging.INFO",
"systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None return",
"root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack()",
"root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root,",
"formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on port %d. Quitting', port) sys.exit(1) except",
"> 1 and sys.argv[1] == '--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s'",
"return True def get_usable_port(): port = 39000 while is_port_in_use(port): # check if wishing",
"a stream handler for log output to stdout root_logger = logging.getLogger() stdout_handler =",
"stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler)",
"does not yet exist if not path.exists(): path.mkdir(parents=True) # path exists, but is",
"from .exceptions import LogNotFoundError def get_data_path(): if sys.platform == 'win32': path = Path(os.environ['APPDATA'])",
"Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port",
"return path def set_up_logging(): log_level = logging.DEBUG if len(sys.argv) > 1 and sys.argv[1]",
"screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2),",
"from urllib.error import URLError, HTTPError from .exceptions import LogNotFoundError def get_data_path(): if sys.platform",
"window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 -",
"port = 39000 while is_port_in_use(port): # check if wishing well is already running",
"logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well')",
"with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port )) return False except",
"log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add a",
"as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on port %d. Quitting',",
"# center the window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth()",
"for log output to stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter",
"def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port )) return",
"on port %d. Quitting', port) sys.exit(1) except (URLError, HTTPError): port += 1 if",
"def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False,",
"import webbrowser from pathlib import Path from tkinter import ttk from urllib.request import",
"is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port )) return False",
"sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else:",
"import urlopen from urllib.error import URLError, HTTPError from .exceptions import LogNotFoundError def get_data_path():",
"port %d. Quitting', port) sys.exit(1) except (URLError, HTTPError): port += 1 if port",
"create dir if it does not yet exist if not path.exists(): path.mkdir(parents=True) #",
"def get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot find the log file on",
"== '--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format,",
"os import socket import sys import tkinter import webbrowser from pathlib import Path",
"try: s.bind(( 'localhost', port )) return False except OSError: return True def get_usable_port():",
"'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack()",
"= '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add a stream",
"0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame,",
"stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try:",
"LogNotFoundError def get_data_path(): if sys.platform == 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif",
"set_up_logging(): log_level = logging.DEBUG if len(sys.argv) > 1 and sys.argv[1] == '--debug' else",
"# add a stream handler for log output to stdout root_logger = logging.getLogger()",
"port += 1 if port == 39010: show_error('No suitable port found.') return port",
"systems.') # create dir if it does not yet exist if not path.exists():",
"== 'linux': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path",
"if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application",
"logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add",
"path.mkdir(parents=True) # path exists, but is a file if not path.is_dir(): show_error(f'{path} already",
"ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the",
"tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame,",
"Path from tkinter import ttk from urllib.request import urlopen from urllib.error import URLError,",
"file.') return path def get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot find the",
"center the window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height",
"Linux based systems.') # create dir if it does not yet exist if",
"file if not path.is_dir(): show_error(f'{path} already exists, but is a file.') return path",
"/ 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None return path def set_up_logging(): log_level",
"ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight()",
"/ 'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME'])",
"= root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width /",
"import LogNotFoundError def get_data_path(): if sys.platform == 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well'",
"output to stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format)",
"running on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing",
"= logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing",
"s.bind(( 'localhost', port )) return False except OSError: return True def get_usable_port(): port",
"root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2), int(screen_height /",
"root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2), int(screen_height / 2 - window_height /",
"# create dir if it does not yet exist if not path.exists(): path.mkdir(parents=True)",
"= Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed to run on Windows",
"port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already",
"get_usable_port(): port = 39000 while is_port_in_use(port): # check if wishing well is already",
"ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window window_width =",
"already exists, but is a file.') return path def get_log_path(): if sys.platform !=",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port )) return False except OSError:",
"'--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level)",
"sys.platform != 'win32': raise LogNotFoundError('Cannot find the log file on non-Windows systems.') path",
"path.exists(): return None return path def set_up_logging(): log_level = logging.DEBUG if len(sys.argv) >",
"this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is",
"socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port )) return False except OSError: return",
"show_error('Wishing Well is only designed to run on Windows or Linux based systems.')",
"stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def",
"if not path.exists(): path.mkdir(parents=True) # path exists, but is a file if not",
"== 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME'",
"if sys.platform != 'win32': raise LogNotFoundError('Cannot find the log file on non-Windows systems.')",
"padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window",
"it does not yet exist if not path.exists(): path.mkdir(parents=True) # path exists, but",
"designed to run on Windows or Linux based systems.') # create dir if",
"Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME'",
"return port def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False,",
"if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser()",
"path def get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot find the log file",
"%(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add a stream handler for",
"Support/wishing-well').expanduser() else: show_error('Wishing Well is only designed to run on Windows or Linux",
"exist if not path.exists(): path.mkdir(parents=True) # path exists, but is a file if",
"%(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add a stream handler for log",
"sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else:",
"sys.exit(1) except (URLError, HTTPError): port += 1 if port == 39010: show_error('No suitable",
"# check if wishing well is already running on this port try: with",
"+= 1 if port == 39010: show_error('No suitable port found.') return port def",
"format=log_format, level=log_level) # add a stream handler for log output to stdout root_logger",
"= Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None return path def",
"True def get_usable_port(): port = 39000 while is_port_in_use(port): # check if wishing well",
"window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight()",
"= root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2), int(screen_height",
"'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None return path def set_up_logging(): log_level =",
"on non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return",
"window_width / 2), int(screen_height / 2 - window_height / 2))) root.mainloop() logging.info('Quitting') sys.exit(1)",
"'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser()",
"(URLError, HTTPError): port += 1 if port == 39010: show_error('No suitable port found.')",
"logging.info('Wishing Well is already running on port %d. Quitting', port) sys.exit(1) except (URLError,",
"= Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is",
"suitable port found.') return port def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well')",
"import ttk from urllib.request import urlopen from urllib.error import URLError, HTTPError from .exceptions",
"else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) #",
"sys.platform == 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux': if",
"text='Okay', command=root.destroy).pack() # center the window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width",
"elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well'",
"# path exists, but is a file if not path.is_dir(): show_error(f'{path} already exists,",
"import logging import os import socket import sys import tkinter import webbrowser from",
"handler for log output to stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level)",
"sys import tkinter import webbrowser from pathlib import Path from tkinter import ttk",
"root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind((",
"False except OSError: return True def get_usable_port(): port = 39000 while is_port_in_use(port): #",
"root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2",
"on Windows or Linux based systems.') # create dir if it does not",
"a file if not path.is_dir(): show_error(f'{path} already exists, but is a file.') return",
"root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png'))",
"show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0])",
"if wishing well is already running on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1)",
"get_data_path(): if sys.platform == 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform ==",
"is a file.') return path def get_log_path(): if sys.platform != 'win32': raise LogNotFoundError('Cannot",
"log file on non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not",
"Well is already running on port %d. Quitting', port) sys.exit(1) except (URLError, HTTPError):",
"Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME' in os.environ: path =",
"tkinter import webbrowser from pathlib import Path from tkinter import ttk from urllib.request",
"text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window window_width = root.winfo_reqwidth()",
"'localhost', port )) return False except OSError: return True def get_usable_port(): port =",
"os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform ==",
"URLError, HTTPError from .exceptions import LogNotFoundError def get_data_path(): if sys.platform == 'win32': path",
"len(sys.argv) > 1 and sys.argv[1] == '--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s:",
"running on port %d. Quitting', port) sys.exit(1) except (URLError, HTTPError): port += 1",
"height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center the window window_width = root.winfo_reqwidth() window_height =",
"is only designed to run on Windows or Linux based systems.') # create",
"'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif",
"None return path def set_up_logging(): log_level = logging.DEBUG if len(sys.argv) > 1 and",
"urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on port",
"39010: show_error('No suitable port found.') return port def show_error(message): logging.error(message) root = tkinter.Tk()",
"Well is only designed to run on Windows or Linux based systems.') #",
"'win32': raise LogNotFoundError('Cannot find the log file on non-Windows systems.') path = Path(os.environ['USERPROFILE'])",
"check if wishing well is already running on this port try: with urlopen(f'http://localhost:{port}/wishing-well',",
"= Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME'])",
"== 'darwin': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path",
"stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET,",
"Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame = ttk.Frame(root, padding=10)",
"os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing",
"found.') return port def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0)",
"in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else:",
"tkinter import ttk from urllib.request import urlopen from urllib.error import URLError, HTTPError from",
"pathlib import Path from tkinter import ttk from urllib.request import urlopen from urllib.error",
"window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width",
"def set_up_logging(): log_level = logging.DEBUG if len(sys.argv) > 1 and sys.argv[1] == '--debug'",
"logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost',",
"<reponame>Ennea/wishing-well<filename>wishing_well/util.py import logging import os import socket import sys import tkinter import webbrowser",
"port) sys.exit(1) except (URLError, HTTPError): port += 1 if port == 39010: show_error('No",
"exists, but is a file.') return path def get_log_path(): if sys.platform != 'win32':",
"= ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() # center",
"path.is_dir(): show_error(f'{path} already exists, but is a file.') return path def get_log_path(): if",
"path def set_up_logging(): log_level = logging.DEBUG if len(sys.argv) > 1 and sys.argv[1] ==",
"port def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False)",
"from urllib.request import urlopen from urllib.error import URLError, HTTPError from .exceptions import LogNotFoundError",
"'linux': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path =",
"is already running on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass",
"file on non-Windows systems.') path = Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists():",
"stream handler for log output to stdout root_logger = logging.getLogger() stdout_handler = logging.StreamHandler(sys.stdout)",
"in os.environ: path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform",
"s: try: s.bind(( 'localhost', port )) return False except OSError: return True def",
"import tkinter import webbrowser from pathlib import Path from tkinter import ttk from",
"as s: try: s.bind(( 'localhost', port )) return False except OSError: return True",
"/ 'wishing-well.log'), format=log_format, level=log_level) # add a stream handler for log output to",
"path exists, but is a file if not path.is_dir(): show_error(f'{path} already exists, but",
"if sys.platform == 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux':",
"Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well is only",
"return False except OSError: return True def get_usable_port(): port = 39000 while is_port_in_use(port):",
"= Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if",
"path = Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ: path =",
"is_port_in_use(port): # check if wishing well is already running on this port try:",
"logging.DEBUG if len(sys.argv) > 1 and sys.argv[1] == '--debug' else logging.INFO log_format =",
"def get_data_path(): if sys.platform == 'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform",
"show_error('No suitable port found.') return port def show_error(message): logging.error(message) root = tkinter.Tk() root.title('Wishing",
"well is already running on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _:",
"screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width / 2), int(screen_height / 2",
"show_error(f'{path} already exists, but is a file.') return path def get_log_path(): if sys.platform",
"if len(sys.argv) > 1 and sys.argv[1] == '--debug' else logging.INFO log_format = '%(asctime)s",
"%d. Quitting', port) sys.exit(1) except (URLError, HTTPError): port += 1 if port ==",
"Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(( 'localhost', port ))",
"tkinter.Tk() root.title('Wishing Well') root.minsize(300, 0) root.resizable(False, False) root.iconphoto(False, tkinter.PhotoImage(file=Path(sys.path[0]) / 'icon.png')) frame =",
"= logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as",
"1 if port == 39010: show_error('No suitable port found.') return port def show_error(message):",
"run on Windows or Linux based systems.') # create dir if it does",
"'%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() / 'wishing-well.log'), format=log_format, level=log_level) # add a stream handler",
"root.winfo_reqheight() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry('+{}+{}'.format(int(screen_width / 2 - window_width /",
"port == 39010: show_error('No suitable port found.') return port def show_error(message): logging.error(message) root",
"based systems.') # create dir if it does not yet exist if not",
"and sys.argv[1] == '--debug' else logging.INFO log_format = '%(asctime)s %(levelname)s: %(message)s' logging.basicConfig(filename=(get_data_path() /",
"urllib.request import urlopen from urllib.error import URLError, HTTPError from .exceptions import LogNotFoundError def",
"to run on Windows or Linux based systems.') # create dir if it",
"return None return path def set_up_logging(): log_level = logging.DEBUG if len(sys.argv) > 1",
"'win32': path = Path(os.environ['APPDATA']) / 'wishing-well' elif sys.platform == 'linux': if 'XDG_DATA_HOME' in",
"command=root.destroy).pack() # center the window window_width = root.winfo_reqwidth() window_height = root.winfo_reqheight() screen_width =",
"logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) formatter = logging.Formatter(log_format) stdout_handler.setFormatter(formatter) root_logger.addHandler(stdout_handler) logging.info('Starting Wishing Well') def is_port_in_use(port): with",
"= logging.DEBUG if len(sys.argv) > 1 and sys.argv[1] == '--debug' else logging.INFO log_format",
"import socket import sys import tkinter import webbrowser from pathlib import Path from",
"with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}') logging.info('Wishing Well is already running on",
"Path('~/.local/share/wishing-well').expanduser() elif sys.platform == 'darwin': if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) /",
"or Linux based systems.') # create dir if it does not yet exist",
"frame = ttk.Frame(root, padding=10) frame.pack() ttk.Label(frame, text=message).pack() ttk.Frame(frame, height=5).pack() ttk.Button(frame, text='Okay', command=root.destroy).pack() #",
"webbrowser from pathlib import Path from tkinter import ttk from urllib.request import urlopen",
"if it does not yet exist if not path.exists(): path.mkdir(parents=True) # path exists,",
"yet exist if not path.exists(): path.mkdir(parents=True) # path exists, but is a file",
"urllib.error import URLError, HTTPError from .exceptions import LogNotFoundError def get_data_path(): if sys.platform ==",
"while is_port_in_use(port): # check if wishing well is already running on this port",
"Windows or Linux based systems.') # create dir if it does not yet",
"path = Path(os.environ['XDG_DATA_HOME']) / 'wishing-well' else: path = Path('~/Library/Application Support/wishing-well').expanduser() else: show_error('Wishing Well",
"already running on this port try: with urlopen(f'http://localhost:{port}/wishing-well', timeout=0.1) as _: pass webbrowser.open(f'http://localhost:{port}')",
"if not path.is_dir(): show_error(f'{path} already exists, but is a file.') return path def",
"if not path.exists(): return None return path def set_up_logging(): log_level = logging.DEBUG if",
"HTTPError from .exceptions import LogNotFoundError def get_data_path(): if sys.platform == 'win32': path =",
"if port == 39010: show_error('No suitable port found.') return port def show_error(message): logging.error(message)",
"Path(os.environ['USERPROFILE']) / 'AppData/LocalLow/miHoYo/Genshin Impact/output_log.txt' if not path.exists(): return None return path def set_up_logging():"
] |
[
"pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"]",
"# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A",
"can throw a value error for some strings. pass if parsed_url and re.match(\"bugs.webkit.org\",",
"ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #",
"in the documentation and/or other materials provided with the # distribution. # *",
"2010 Google Inc. All rights reserved. # # Redistribution and use in source",
"run(self, state): # No need to prompt if we alrady have the bug_id.",
"All rights reserved. # # Redistribution and use in source and binary forms,",
"software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY",
"subject. try: state[\"bug_id\"] = int(user_response) except ValueError as TypeError: parsed_url = None try:",
"return user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or a title for",
"a number or a valid bugzilla URL, we assume it's bug number. #",
"# this software without specific prior written permission. # # THIS SOFTWARE IS",
"* Redistributions of source code must retain the above copyright # notice, this",
"state[\"bug_title\"] = user_response # FIXME: This is kind of a lame description. state[\"bug_description\"]",
"# modification, are permitted provided that the following conditions are # met: #",
"try: state[\"bug_id\"] = int(user_response) except ValueError as TypeError: parsed_url = None try: parsed_url",
"you sure you want to create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] =",
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep",
"of conditions and the following disclaimer. # * Redistributions in binary form must",
"[ Options.non_interactive, ] def run(self, state): # No need to prompt if we",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY",
"Google Inc. nor the names of its # contributors may be used to",
"with a number or a valid bugzilla URL, we assume it's bug number.",
"urlparse(user_response) except ValueError: # urlparse can throw a value error for some strings.",
"PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR",
"and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return",
"BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE",
"assume it's a bug subject. try: state[\"bug_id\"] = int(user_response) except ValueError as TypeError:",
"number/bugzilla URL or a title for a new bug:\\n\") # If the user",
"this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED",
"TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR",
"without # modification, are permitted provided that the following conditions are # met:",
"this list of conditions and the following disclaimer. # * Redistributions in binary",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED",
"NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,",
"+ [ Options.non_interactive, ] def run(self, state): # No need to prompt if",
"and/or other materials provided with the # distribution. # * Neither the name",
"with or without # modification, are permitted provided that the following conditions are",
"conditions and the following disclaimer. # * Redistributions in binary form must reproduce",
"other materials provided with the # distribution. # * Neither the name of",
"return if not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you want to create",
"# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #",
"(3, 0): from urllib.parse import urlparse else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep):",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED.",
"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN",
"# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #",
"re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if",
"= int(match.group(\"bug_id\")) return if not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you want",
"self._tool.user.confirm(\"Are you sure you want to create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"]",
"endorse or promote products derived from # this software without specific prior written",
"state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or a title",
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER",
"have the bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla",
"the documentation and/or other materials provided with the # distribution. # * Neither",
"No need to prompt if we alrady have the bug_id. if state.get(\"bug_id\"): return",
"Options if sys.version_info > (3, 0): from urllib.parse import urlparse else: from urlparse",
"the user responds with a number or a valid bugzilla URL, we assume",
"WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF",
"above copyright # notice, this list of conditions and the following disclaimer. #",
"DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #",
"NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #",
"list of conditions and the following disclaimer. # * Redistributions in binary form",
"rights reserved. # # Redistribution and use in source and binary forms, with",
"a valid bugzilla URL, we assume it's bug number. # Otherwise we assume",
"import re import sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options if",
"OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER",
"throw a value error for some strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc):",
"# urlparse can throw a value error for some strings. pass if parsed_url",
"permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"a bug subject. try: state[\"bug_id\"] = int(user_response) except ValueError as TypeError: parsed_url =",
"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE,",
"THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF",
"state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you",
"OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR",
"or without # modification, are permitted provided that the following conditions are #",
"# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #",
"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE)",
"with the # distribution. # * Neither the name of Google Inc. nor",
"ValueError as TypeError: parsed_url = None try: parsed_url = urlparse(user_response) except ValueError: #",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND",
"notice, this list of conditions and the following disclaimer # in the documentation",
"parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not",
"new bug:\\n\") # If the user responds with a number or a valid",
"SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,",
"alrady have the bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a bug",
"NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY",
"COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"parsed_url = urlparse(user_response) except ValueError: # urlparse can throw a value error for",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT",
"= user_response # FIXME: This is kind of a lame description. state[\"bug_description\"] =",
"user_response # FIXME: This is kind of a lame description. state[\"bug_description\"] = user_response",
"a title for a new bug:\\n\") # If the user responds with a",
"distribution. # * Neither the name of Google Inc. nor the names of",
"without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE",
"sys.version_info > (3, 0): from urllib.parse import urlparse else: from urlparse import urlparse",
"(C) 2010 Google Inc. All rights reserved. # # Redistribution and use in",
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re",
"= re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive and",
"ValueError: # urlparse can throw a value error for some strings. pass if",
"code must retain the above copyright # notice, this list of conditions and",
"# in the documentation and/or other materials provided with the # distribution. #",
"ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT",
"conditions are # met: # # * Redistributions of source code must retain",
"following conditions are # met: # # * Redistributions of source code must",
"SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED",
"Redistributions in binary form must reproduce the above # copyright notice, this list",
"match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure",
"OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR",
"self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or a title for a new bug:\\n\")",
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS",
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY",
"Google Inc. All rights reserved. # # Redistribution and use in source and",
"0): from urllib.parse import urlparse else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod",
"URL, we assume it's bug number. # Otherwise we assume it's a bug",
"if we alrady have the bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter",
"provided with the # distribution. # * Neither the name of Google Inc.",
"bug number/bugzilla URL or a title for a new bug:\\n\") # If the",
"# Otherwise we assume it's a bug subject. try: state[\"bug_id\"] = int(user_response) except",
"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY,",
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF",
"AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"and use in source and binary forms, with or without # modification, are",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED",
"urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.non_interactive, ] def",
"the following conditions are # met: # # * Redistributions of source code",
"the name of Google Inc. nor the names of its # contributors may",
"need to prompt if we alrady have the bug_id. if state.get(\"bug_id\"): return user_response",
"AbstractStep.options() + [ Options.non_interactive, ] def run(self, state): # No need to prompt",
"CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES",
"from urllib.parse import urlparse else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def",
"# * Redistributions of source code must retain the above copyright # notice,",
"bug number. # Otherwise we assume it's a bug subject. try: state[\"bug_id\"] =",
"match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive",
"for a new bug:\\n\") # If the user responds with a number or",
"# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and",
"not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you want to create a new",
"except ValueError: # urlparse can throw a value error for some strings. pass",
"OF SUCH DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options",
"Inc. All rights reserved. # # Redistribution and use in source and binary",
"of its # contributors may be used to endorse or promote products derived",
"its # contributors may be used to endorse or promote products derived from",
"(INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS",
"# met: # # * Redistributions of source code must retain the above",
"def run(self, state): # No need to prompt if we alrady have the",
"class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.non_interactive, ] def run(self,",
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA,",
"OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"or a valid bugzilla URL, we assume it's bug number. # Otherwise we",
"for some strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query)",
"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS",
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING",
"value error for some strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match =",
"contributors may be used to endorse or promote products derived from # this",
"permitted provided that the following conditions are # met: # # * Redistributions",
"must retain the above copyright # notice, this list of conditions and the",
"a value error for some strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match",
"the bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla URL",
"* Redistributions in binary form must reproduce the above # copyright notice, this",
"default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME: This is kind of a lame",
"Redistribution and use in source and binary forms, with or without # modification,",
"source and binary forms, with or without # modification, are permitted provided that",
"name of Google Inc. nor the names of its # contributors may be",
"int(user_response) except ValueError as TypeError: parsed_url = None try: parsed_url = urlparse(user_response) except",
"BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\"",
"Redistributions of source code must retain the above copyright # notice, this list",
"modification, are permitted provided that the following conditions are # met: # #",
"STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY",
"notice, this list of conditions and the following disclaimer. # * Redistributions in",
"derived from # this software without specific prior written permission. # # THIS",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN",
"SUCH DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import",
"If the user responds with a number or a valid bugzilla URL, we",
"IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR",
"a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME: This is kind",
"are permitted provided that the following conditions are # met: # # *",
"# contributors may be used to endorse or promote products derived from #",
"materials provided with the # distribution. # * Neither the name of Google",
"number. # Otherwise we assume it's a bug subject. try: state[\"bug_id\"] = int(user_response)",
"int(match.group(\"bug_id\")) return if not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you want to",
"some strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS",
"EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,",
"urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.non_interactive,",
"bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME: This is kind of a",
"parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive and not self._tool.user.confirm(\"Are",
"user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or a title for a",
"forms, with or without # modification, are permitted provided that the following conditions",
"a bug number/bugzilla URL or a title for a new bug:\\n\") # If",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import",
"source code must retain the above copyright # notice, this list of conditions",
"FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR",
"> (3, 0): from urllib.parse import urlparse else: from urlparse import urlparse class",
"options(cls): return AbstractStep.options() + [ Options.non_interactive, ] def run(self, state): # No need",
"in source and binary forms, with or without # modification, are permitted provided",
"else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() +",
"enter a bug number/bugzilla URL or a title for a new bug:\\n\") #",
"assume it's bug number. # Otherwise we assume it's a bug subject. try:",
"following disclaimer. # * Redistributions in binary form must reproduce the above #",
"disclaimer. # * Redistributions in binary form must reproduce the above # copyright",
"IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF",
"disclaimer # in the documentation and/or other materials provided with the # distribution.",
"it's a bug subject. try: state[\"bug_id\"] = int(user_response) except ValueError as TypeError: parsed_url",
"# # Redistribution and use in source and binary forms, with or without",
"of Google Inc. nor the names of its # contributors may be used",
"and the following disclaimer # in the documentation and/or other materials provided with",
"AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR",
"above # copyright notice, this list of conditions and the following disclaimer #",
"Otherwise we assume it's a bug subject. try: state[\"bug_id\"] = int(user_response) except ValueError",
"OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER",
"form must reproduce the above # copyright notice, this list of conditions and",
"used to endorse or promote products derived from # this software without specific",
"IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN",
"re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive and not",
"list of conditions and the following disclaimer # in the documentation and/or other",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR",
"we assume it's bug number. # Otherwise we assume it's a bug subject.",
"from webkitpy.tool.steps.options import Options if sys.version_info > (3, 0): from urllib.parse import urlparse",
"user responds with a number or a valid bugzilla URL, we assume it's",
"promote products derived from # this software without specific prior written permission. #",
"and not self._tool.user.confirm(\"Are you sure you want to create a new bug?\", default=\"n\"):",
"COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #",
"prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"TypeError: parsed_url = None try: parsed_url = urlparse(user_response) except ValueError: # urlparse can",
"ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"want to create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME:",
"# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #",
"import Options if sys.version_info > (3, 0): from urllib.parse import urlparse else: from",
"Neither the name of Google Inc. nor the names of its # contributors",
"HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT",
"from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info > (3, 0):",
"PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.non_interactive, ] def run(self, state):",
"def options(cls): return AbstractStep.options() + [ Options.non_interactive, ] def run(self, state): # No",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE",
"IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO,",
"use in source and binary forms, with or without # modification, are permitted",
"try: parsed_url = urlparse(user_response) except ValueError: # urlparse can throw a value error",
"OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF",
"= self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or a title for a new",
"CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,",
"import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.non_interactive, ]",
"to endorse or promote products derived from # this software without specific prior",
"# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS",
"AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info > (3, 0): from urllib.parse import",
"EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import sys",
"if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] =",
"# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL,",
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED",
"URL or a title for a new bug:\\n\") # If the user responds",
"re import sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info",
"parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match: state[\"bug_id\"] = int(match.group(\"bug_id\"))",
"number or a valid bugzilla URL, we assume it's bug number. # Otherwise",
"HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"we assume it's a bug subject. try: state[\"bug_id\"] = int(user_response) except ValueError as",
"valid bugzilla URL, we assume it's bug number. # Otherwise we assume it's",
"products derived from # this software without specific prior written permission. # #",
"USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY",
"and the following disclaimer. # * Redistributions in binary form must reproduce the",
"# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING",
"must reproduce the above # copyright notice, this list of conditions and the",
"not self._tool.user.confirm(\"Are you sure you want to create a new bug?\", default=\"n\"): self._exit(1)",
"# * Neither the name of Google Inc. nor the names of its",
"DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options",
"] def run(self, state): # No need to prompt if we alrady have",
"# copyright notice, this list of conditions and the following disclaimer # in",
"documentation and/or other materials provided with the # distribution. # * Neither the",
"from # this software without specific prior written permission. # # THIS SOFTWARE",
"urllib.parse import urlparse else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls):",
"= int(user_response) except ValueError as TypeError: parsed_url = None try: parsed_url = urlparse(user_response)",
"prompt if we alrady have the bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please",
"LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"be used to endorse or promote products derived from # this software without",
"OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO",
"# No need to prompt if we alrady have the bug_id. if state.get(\"bug_id\"):",
"to create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME: This",
"USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH",
"= urlparse(user_response) except ValueError: # urlparse can throw a value error for some",
"BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME: This is",
"@classmethod def options(cls): return AbstractStep.options() + [ Options.non_interactive, ] def run(self, state): #",
"OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS",
"and binary forms, with or without # modification, are permitted provided that the",
"names of its # contributors may be used to endorse or promote products",
"responds with a number or a valid bugzilla URL, we assume it's bug",
"AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY",
"# If the user responds with a number or a valid bugzilla URL,",
"TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE",
"WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #",
"copyright notice, this list of conditions and the following disclaimer # in the",
"ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED",
"title for a new bug:\\n\") # If the user responds with a number",
"ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN",
"the # distribution. # * Neither the name of Google Inc. nor the",
"provided that the following conditions are # met: # # * Redistributions of",
"OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR",
"new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response # FIXME: This is kind of",
"FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE",
"from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [",
"INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT,",
"sure you want to create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response",
"CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF",
"met: # # * Redistributions of source code must retain the above copyright",
"self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you want to create a new bug?\",",
"we alrady have the bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a",
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR",
"following disclaimer # in the documentation and/or other materials provided with the #",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF",
"webkitpy.tool.steps.options import Options if sys.version_info > (3, 0): from urllib.parse import urlparse else:",
"urlparse else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return AbstractStep.options()",
"state): # No need to prompt if we alrady have the bug_id. if",
"except ValueError as TypeError: parsed_url = None try: parsed_url = urlparse(user_response) except ValueError:",
"THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE",
"# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT",
"in binary form must reproduce the above # copyright notice, this list of",
"of conditions and the following disclaimer # in the documentation and/or other materials",
"None try: parsed_url = urlparse(user_response) except ValueError: # urlparse can throw a value",
"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE",
"sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info > (3,",
"webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info > (3, 0): from",
"bug subject. try: state[\"bug_id\"] = int(user_response) except ValueError as TypeError: parsed_url = None",
"as TypeError: parsed_url = None try: parsed_url = urlparse(user_response) except ValueError: # urlparse",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import",
"= None try: parsed_url = urlparse(user_response) except ValueError: # urlparse can throw a",
"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS",
"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"the above # copyright notice, this list of conditions and the following disclaimer",
"you want to create a new bug?\", default=\"n\"): self._exit(1) state[\"bug_title\"] = user_response #",
"ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE",
"bugzilla URL, we assume it's bug number. # Otherwise we assume it's a",
"the following disclaimer. # * Redistributions in binary form must reproduce the above",
"or a title for a new bug:\\n\") # If the user responds with",
"are # met: # # * Redistributions of source code must retain the",
"# * Redistributions in binary form must reproduce the above # copyright notice,",
"MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT",
"a new bug:\\n\") # If the user responds with a number or a",
"* Neither the name of Google Inc. nor the names of its #",
"self._exit(1) state[\"bug_title\"] = user_response # FIXME: This is kind of a lame description.",
"the names of its # contributors may be used to endorse or promote",
"retain the above copyright # notice, this list of conditions and the following",
"conditions and the following disclaimer # in the documentation and/or other materials provided",
"parsed_url = None try: parsed_url = urlparse(user_response) except ValueError: # urlparse can throw",
"state[\"bug_id\"] = int(user_response) except ValueError as TypeError: parsed_url = None try: parsed_url =",
"urlparse can throw a value error for some strings. pass if parsed_url and",
"reserved. # # Redistribution and use in source and binary forms, with or",
"error for some strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\",",
"Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use",
"# Redistribution and use in source and binary forms, with or without #",
"binary form must reproduce the above # copyright notice, this list of conditions",
"bug_id. if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or",
"nor the names of its # contributors may be used to endorse or",
"OF THE POSSIBILITY OF SUCH DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep import",
"import sys from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info >",
"the following disclaimer # in the documentation and/or other materials provided with the",
"that the following conditions are # met: # # * Redistributions of source",
"DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF",
"return AbstractStep.options() + [ Options.non_interactive, ] def run(self, state): # No need to",
"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS;",
"if state.get(\"bug_id\"): return user_response = self._tool.user.prompt(\"Please enter a bug number/bugzilla URL or a",
"OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON",
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,",
"if sys.version_info > (3, 0): from urllib.parse import urlparse else: from urlparse import",
"TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE",
"binary forms, with or without # modification, are permitted provided that the following",
"of source code must retain the above copyright # notice, this list of",
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY,",
"# distribution. # * Neither the name of Google Inc. nor the names",
"reproduce the above # copyright notice, this list of conditions and the following",
"# notice, this list of conditions and the following disclaimer. # * Redistributions",
"may be used to endorse or promote products derived from # this software",
"this list of conditions and the following disclaimer # in the documentation and/or",
"import AbstractStep from webkitpy.tool.steps.options import Options if sys.version_info > (3, 0): from urllib.parse",
"# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #",
"THE POSSIBILITY OF SUCH DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep import AbstractStep",
"Inc. nor the names of its # contributors may be used to endorse",
"the above copyright # notice, this list of conditions and the following disclaimer.",
"POSSIBILITY OF SUCH DAMAGE. import re import sys from webkitpy.tool.steps.abstractstep import AbstractStep from",
"THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"bug:\\n\") # If the user responds with a number or a valid bugzilla",
"INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED",
"GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION)",
"LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT",
"to prompt if we alrady have the bug_id. if state.get(\"bug_id\"): return user_response =",
"if not self._options.non_interactive and not self._tool.user.confirm(\"Are you sure you want to create a",
"OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY",
"INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"import urlparse else: from urlparse import urlparse class PromptForBugOrTitle(AbstractStep): @classmethod def options(cls): return",
"# # * Redistributions of source code must retain the above copyright #",
"if match: state[\"bug_id\"] = int(match.group(\"bug_id\")) return if not self._options.non_interactive and not self._tool.user.confirm(\"Are you",
"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import sys from",
"# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"it's bug number. # Otherwise we assume it's a bug subject. try: state[\"bug_id\"]",
"Options.non_interactive, ] def run(self, state): # No need to prompt if we alrady",
"written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"or promote products derived from # this software without specific prior written permission.",
"INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO,",
"specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"strings. pass if parsed_url and re.match(\"bugs.webkit.org\", parsed_url.netloc): match = re.match(\"id=(?P<bug_id>\\d+)\", parsed_url.query) if match:",
"copyright # notice, this list of conditions and the following disclaimer. # *"
] |
[
"this threshold, the null answer is selected for this example (note that the",
"Unless required by applicable law or agreed to in writing, software # distributed",
"def tokenize(text): # return text.split(\" \") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def",
"answers, are saved in `output_dir`. prefix (:obj:`str`, `optional`): If provided, the dictionaries mentioned",
"\"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} ) # Compute the softmax of",
"ban_word in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( {",
"remove answers that do not have the maximum context # available in the",
"= pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare",
"\"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index],",
"a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json,",
"more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model: two arrays containing",
"License. \"\"\" Pre-processing Post-processing utilities for question answering. \"\"\" import collections import json",
"is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split into {len(features)} features.\" )",
"\"This example script only works for models that have a fast tokenizer. Checkout",
"import json import logging import os from typing import Optional, Tuple import numpy",
"saved with `prefix` added to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`):",
"start and end logits. Args: examples: The non-preprocessed dataset (see the main script",
"all features must be aligned on the fact they `want` to predict a",
"model types that meet this \" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn(",
"{prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds",
"#all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable by casting np.float",
"first dimension must match the number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`,",
"{len(features)} features.\" ) # Let's loop over all the examples! for example_index, example",
"to stay independent from torch/tf in this file, using # the LogSumExp trick).",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint",
"import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\"",
"= Mecab() def tokenize(text): # return text.split(\" \") return mecab.morphs(text) def sigmoid(x): return",
"offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we will remove answers that",
"``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed to",
"examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size: int = 20,",
"\"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab()",
"if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json,",
"`optional`): If provided, the dictionaries of predictions, n_best predictions (with their scores and",
"to :obj:`True`): Whether this process is the main process or not (used to",
"such information is # provided). if ( token_is_max_context is not None and not",
"raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not empty. \" \"Use",
"the scores differences between best and null answers, are saved in `output_dir`. prefix",
"#\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative: # Add the",
"import os from typing import Optional, Tuple import numpy as np from tqdm.auto",
"number of n-best predictions to generate when looking for an answer. max_answer_length (:obj:`int`,",
"(0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go through all",
"are not conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The",
"casting np.float back to float. all_nbest_json[example[\"id\"]] = [ { k: ( float(v) if",
"# Update minimum null prediction. feature_null_score = start_logits[0] + end_logits[0] if ( min_null_prediction",
"all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we first need to find the best",
"file, using # the LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred in predictions])",
"\" \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\" ) # Tokenizer",
"answer for an example giving several features is the minimum of the scores",
":obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the dictionaries of predictions, n_best",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"the `n_best_size` greater start and end logits. start_indexes = np.argsort(start_logits)[ -1 : -consider",
"else v ) for k, v in pred.items() } for pred in predictions",
"If the null answer is not possible, this is easy. if not version_2_with_negative:",
"the softmax of all scores (we do it with numpy to stay independent",
"the dictionaries mentioned above are saved with `prefix` added to their names. is_world_process_zero",
"start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what will allow us",
">= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is",
"consider answers with a length that is either < 0 or > max_answer_length.",
"`prefix` added to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this",
"for pred in predictions ] # If we have an output_dir, let's save",
"None or offset_mapping[end_index] is None ): continue # Don't consider answers with a",
"is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\",",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"Whether or not the underlying dataset contains examples with no answers. n_best_size (:obj:`int`,",
"the best answer has a score that is less than the score of",
"Build a map example to its corresponding features. example_id_to_index = {k: i for",
"processed dataset (see the main script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The",
"candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": (",
"dictionaries of predictions, n_best predictions (with their scores and logits) and, if :obj:`version_2_with_negative=True`,",
"in the context. if ( start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or",
"{nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative:",
"len(predictions) == 1 and predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\":",
"with numpy to stay independent from torch/tf in this file, using # the",
"Mecab import torch import random from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import",
"{null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions",
"np.ndarray], version_2_with_negative: bool = False, n_best_size: int = 20, max_answer_length: int = 30,",
"def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size: int",
"= os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative:",
"None ) # Update minimum null prediction. feature_null_score = start_logits[0] + end_logits[0] if",
"( token_is_max_context is not None and not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]]",
"we have to fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json",
"failure. if len(predictions) == 0 or ( len(predictions) == 1 and predictions[0][\"text\"] ==",
"all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions`",
"logits. Args: examples: The non-preprocessed dataset (see the main script for more information).",
"This is needed because the start and end predictions are not conditioned on",
": -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist() for",
"names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this process is the main",
"not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word",
"gather the answer text in the original context. context = example[\"context\"] for pred",
"prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add back the minimum null prediction",
"the context. if ( start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index]",
"our logits to span of texts in the original # context. offset_mapping =",
"and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed to set. \"\"\" random.seed(seed)",
"bool = False, n_best_size: int = 20, max_answer_length: int = 30, null_score_diff_threshold: float",
"the dictionaries of predictions, n_best predictions (with their scores and logits) and, if",
"or add `--overwrite_output_dir` to train from scratch.\" ) # Tokenizer check: this script",
"that is either < 0 or > max_answer_length. if ( end_index < start_index",
"substrings of the original contexts. This is the base postprocessing functions for models",
"null answer minus this threshold, the null answer is selected for this example",
"predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add back the",
"if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory ({training_args.output_dir})",
"# return text.split(\" \") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int):",
"predictions of a question-answering model to convert them to answers that are substrings",
"either < 0 or > max_answer_length. if ( end_index < start_index or end_index",
"the probabilities in our predictions. for prob, pred in zip(probs, predictions): pred[\"probability\"] =",
"training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and",
"the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) # Update minimum null",
"This is what will allow us to map some the positions in our",
"= get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output",
"original contexts. This is the base postprocessing functions for models that only return",
"this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we",
"if ( start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is None",
"\"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable by",
"`optional`): If provided, the dictionaries mentioned above are saved with `prefix` added to",
"not use this file except in compliance with the License. # You may",
"0.0, \"end_logit\": 0.0, \"score\": 0.0} ) # Compute the softmax of all scores",
"consider out-of-scope answers, either because the indices are out of bounds or correspond",
"an output_dir, let's save all those dicts. if output_dir is not None: assert",
"(with their scores and logits) and, if :obj:`version_2_with_negative=True`, the dictionary of the scores",
"= all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what will allow us to",
"+ \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer:",
"len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not",
"> max_answer_length. if ( end_index < start_index or end_index - start_index + 1",
"them to answers that are substrings of the original contexts. This is the",
"- best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff ) # To be JSON-serializable. if",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"examples with no answers. n_best_size (:obj:`int`, `optional`, defaults to 20): The total number",
"( start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is None or",
"): \"\"\" Post-processes the predictions of a question-answering model to convert them to",
"== 1 and predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0,",
"model: two arrays containing the start logits and the end logits respectively. Its",
"os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file",
"for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf``",
"prediction. i = 0 while predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred =",
"is the base postprocessing functions for models that only return start and end",
"agreed to in writing, software # distributed under the License is distributed on",
"+ \"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last checkpoint.",
"defaults to :obj:`True`): Whether this process is the main process or not (used",
"[ { k: ( float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v )",
"or end_index - start_index + 1 > max_answer_length ): continue # Don't consider",
"the original contexts. This is the base postprocessing functions for models that only",
"the input_ids that are not in the context. if ( start_index >= len(offset_mapping)",
"(note that the score of the null answer for an example giving several",
"(:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the underlying dataset contains examples",
"best prediction. If the null answer is not possible, this is easy. if",
"#print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge case we have not a single",
"start_index in start_indexes: for end_index in end_indexes: # Don't consider out-of-scope answers, either",
"if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark",
"({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets:",
"and end logits. Args: examples: The non-preprocessed dataset (see the main script for",
"dictionaries we have to fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative:",
"all those dicts. if output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir} is not",
"np.max(scores)) probs = exp_scores / exp_scores.sum() # Include the probabilities in our predictions.",
"float. all_nbest_json[example[\"id\"]] = [ { k: ( float(v) if isinstance(v, (np.float16, np.float32, np.float64))",
"with a length that is either < 0 or > max_answer_length. if (",
") max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets: raise ValueError(\"--do_eval requires",
"reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if",
"# Detecting last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and",
"to in writing, software # distributed under the License is distributed on an",
"saved in `output_dir`. prefix (:obj:`str`, `optional`): If provided, the dictionaries mentioned above are",
"implied. # See the License for the specific language governing permissions and #",
"the fact they `want` to predict a null answer). Only useful when :obj:`version_2_with_negative`",
"(we do it with numpy to stay independent from torch/tf in this file,",
"and logits) and, if :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best",
"its low score. if version_2_with_negative and not any( p[\"offsets\"] == (0, 0) for",
"{len(features)} features.\" # Build a map example to its corresponding features. example_id_to_index =",
"the features associated to the current example. for feature_index in feature_indices: # We",
"of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this",
"possible, this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise",
"was removed because of its low score. if version_2_with_negative and not any( p[\"offsets\"]",
"Then we compare to the null prediction using the threshold. score_diff = (",
"best answer has a score that is less than the score of the",
"under the License. \"\"\" Pre-processing Post-processing utilities for question answering. \"\"\" import collections",
"that have a fast tokenizer. Checkout the big table of models \" \"at",
"useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the dictionaries of",
"for feature_index in feature_indices: # We grab the predictions of the model for",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what will allow us to map",
"prediction using the threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] )",
"numpy to stay independent from torch/tf in this file, using # the LogSumExp",
"# If we have an output_dir, let's save all those dicts. if output_dir",
"if prefix is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join( output_dir,",
"tokenizer. Checkout the big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the",
"np.float32, np.float64)) else v ) for k, v in pred.items() } for pred",
"The predictions of the model: two arrays containing the start logits and the",
"Include the probabilities in our predictions. for prob, pred in zip(probs, predictions): pred[\"probability\"]",
"not None: assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file = os.path.join( output_dir,",
"they `want` to predict a null answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`.",
":obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null answers, are",
"in enumerate(tqdm(examples)): # Those are the indices of the features associated to the",
"int = 30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str] = None, prefix: Optional[str]",
"np from tqdm.auto import tqdm from konlpy.tag import Mecab import torch import random",
"prediction, we create a fake prediction to avoid # failure. if len(predictions) ==",
"this file, using # the LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred in",
"indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions = [] # Looping through all",
"float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v ) for k, v in",
"script for more information). features: The processed dataset (see the main script for",
"directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json, )",
"def set_seed(seed: int): \"\"\" Helper function for reproducible behavior to set the seed",
"- np.max(scores)) probs = exp_scores / exp_scores.sum() # Include the probabilities in our",
"and not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if",
"consider=20 ): \"\"\" Post-processes the predictions of a question-answering model to convert them",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"# context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we will remove",
"\"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text): # return",
"not None and not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in",
"None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = { \"offsets\": (0, 0), \"score\":",
"\"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join(",
"enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to fill. all_predictions = collections.OrderedDict() all_nbest_json",
",\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab =",
"version_2_with_negative: bool = False, n_best_size: int = 20, max_answer_length: int = 30, null_score_diff_threshold:",
"logits and the end logits respectively. Its first dimension must match the number",
"in the original # context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided",
"( end_index < start_index or end_index - start_index + 1 > max_answer_length ):",
"= start_logits[0] + end_logits[0] if ( min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score",
"== (0, 0) for p in predictions ): predictions.append(min_null_prediction) # Use the offsets",
"Those are the indices of the features associated to the current example. feature_indices",
"the maximum length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length,",
"dictionary of the scores differences between best and null answers, are saved in",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"avoid # failure. if len(predictions) == 0 or ( len(predictions) == 1 and",
"two elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0]) == len( features",
"scores for the null answer on each feature: all features must be aligned",
"create a fake prediction to avoid # failure. if len(predictions) == 0 or",
"and not any( p[\"offsets\"] == (0, 0) for p in predictions ): predictions.append(min_null_prediction)",
"are saved in `output_dir`. prefix (:obj:`str`, `optional`): If provided, the dictionaries mentioned above",
"best and null answers, are saved in `output_dir`. prefix (:obj:`str`, `optional`): If provided,",
"features_per_example[example_index] min_null_prediction = None prelim_predictions = [] # Looping through all the features",
"in end_indexes: # Don't consider out-of-scope answers, either because the indices are out",
"== 0 or ( len(predictions) == 1 and predictions[0][\"text\"] == \"\" ): predictions.insert(",
": -consider - 1 : -1].tolist() for start_index in start_indexes: for end_index in",
"writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): #",
"max_answer_length (:obj:`int`, `optional`, defaults to 30): The maximum length of an answer that",
"numpy as np from tqdm.auto import tqdm from konlpy.tag import Mecab import torch",
"in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In",
"predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred = predictions[i] # Then we compare",
"is None or offset_mapping[end_index] is None ): continue # Don't consider answers with",
"features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we",
") # Tokenizer check: this script requires a fast tokenizer. if not isinstance(tokenizer,",
"part of the input_ids that are not in the context. if ( start_index",
"torch import random from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger",
"length of an answer that can be generated. This is needed because the",
"features must be aligned on the fact they `want` to predict a null",
"] # If we have an output_dir, let's save all those dicts. if",
"null answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided,",
"for prob, pred in zip(probs, predictions): pred[\"probability\"] = prob # Pick the best",
"print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index],",
"predict a null answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`):",
") nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json, )",
"output_dir, let's save all those dicts. if output_dir is not None: assert os.path.isdir(output_dir),",
"from torch/tf in this file, using # the LogSumExp trick). scores = np.array([pred.pop(\"score\")",
"# Only keep the best `n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda x:",
"independent from torch/tf in this file, using # the LogSumExp trick). scores =",
"\"score\": 0.0} ) # Compute the softmax of all scores (we do it",
"\"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with",
"for more information). features: The processed dataset (see the main script for more",
"answers that do not have the maximum context # available in the current",
"to determine if logging/saves should be done). \"\"\" assert ( len(predictions) == 2",
"\"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go through all possibilities for the `n_best_size`",
"to the null prediction using the threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"]",
"have to fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json =",
"start logits and the end logits respectively. Its first dimension must match the",
"is larger than the maximum length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" )",
"example (note that the score of the null answer for an example giving",
"for p in predictions ): predictions.append(min_null_prediction) # Use the offsets to gather the",
"\"\"\" Pre-processing Post-processing utilities for question answering. \"\"\" import collections import json import",
"def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function for reproducible behavior",
"PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\",",
"collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to",
"torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False",
"end_index < start_index or end_index - start_index + 1 > max_answer_length ): continue",
"end_logits[0], } # Go through all possibilities for the `n_best_size` greater start and",
"out of bounds or correspond # to part of the input_ids that are",
"the best non-empty prediction. i = 0 while predictions[i][\"text\"] == \"\": i +=",
"if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features,",
"transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\",",
"null prediction if it was removed because of its low score. if version_2_with_negative",
"start and end logits. start_indexes = np.argsort(start_logits)[ -1 : -consider - 1 :",
"models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this \"",
"\"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\")",
"\"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text):",
"training at {last_checkpoint}. To avoid this behavior, change \" \"the `--output_dir` or add",
"features associated to the current example. for feature_index in feature_indices: # We grab",
"# Build a map example to its corresponding features. example_id_to_index = {k: i",
"random from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__)",
"start_indexes: for end_index in end_indexes: # Don't consider out-of-scope answers, either because the",
"{len(predictions[0])} predictions and {len(features)} features.\" # Build a map example to its corresponding",
"allow us to map some the positions in our logits to span of",
"any( p[\"offsets\"] == (0, 0) for p in predictions ): predictions.append(min_null_prediction) # Use",
"context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge case we have",
"functions for models that only return start and end logits. Args: examples: The",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"): continue # Don't consider answer that don't have the maximum context available",
"\"\": i += 1 best_non_null_pred = predictions[i] # Then we compare to the",
"generated. This is needed because the start and end predictions are not conditioned",
"predictions (with their scores and logits) and, if :obj:`version_2_with_negative=True`, the dictionary of the",
"(start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0]) == len( features ), f\"Got",
"main process or not (used to determine if logging/saves should be done). \"\"\"",
"all possibilities for the `n_best_size` greater start and end logits. start_indexes = np.argsort(start_logits)[",
"need to find the best non-empty prediction. i = 0 while predictions[i][\"text\"] ==",
"> max_answer_length ): continue # Don't consider answer that don't have the maximum",
"is # provided). if ( token_is_max_context is not None and not token_is_max_context.get(str(start_index), False)",
"# provided). if ( token_is_max_context is not None and not token_is_max_context.get(str(start_index), False) ):",
"offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very",
"offset_mapping[start_index] is None or offset_mapping[end_index] is None ): continue # Don't consider answers",
"the minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep the best",
"language governing permissions and # limitations under the License. \"\"\" Pre-processing Post-processing utilities",
"See the License for the specific language governing permissions and # limitations under",
"\"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} )",
"n_best_size: int = 20, max_answer_length: int = 30, null_score_diff_threshold: float = 0.0, output_dir:",
"the model types that meet this \" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length:",
"os from typing import Optional, Tuple import numpy as np from tqdm.auto import",
"Args: examples: The non-preprocessed dataset (see the main script for more information). features:",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"selected for this example (note that the score of the null answer for",
"in pred.items() } for pred in predictions ] # If we have an",
"None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix",
"on each feature: all features must be aligned on the fact they `want`",
"Compute the softmax of all scores (we do it with numpy to stay",
"map example to its corresponding features. example_id_to_index = {k: i for i, k",
"containing the start logits and the end logits respectively. Its first dimension must",
"for models that have a fast tokenizer. Checkout the big table of models",
"torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool =",
"because the start and end predictions are not conditioned on one another. null_score_diff_threshold",
"or not (used to determine if logging/saves should be done). \"\"\" assert (",
"\"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic",
"0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go through all possibilities",
"null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep the best `n_best_size` predictions.",
"passed ({data_args.max_seq_length}) is larger than the maximum length for the\" f\"model ({tokenizer.model_max_length}). Using",
"should be a tuple with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions",
"be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"]",
"`--overwrite_output_dir` to train from scratch.\" ) # Tokenizer check: this script requires a",
"question answering. \"\"\" import collections import json import logging import os from typing",
"above are saved with `prefix` added to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults",
"to select the null answer: if the best answer has a score that",
"null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make",
"False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size:",
"check: this script requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError(",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"answer. max_answer_length (:obj:`int`, `optional`, defaults to 30): The maximum length of an answer",
"answering. \"\"\" import collections import json import logging import os from typing import",
"= logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\",",
"# Don't consider answer that don't have the maximum context available (if such",
"postprocessing functions for models that only return start and end logits. Args: examples:",
"# Those are the indices of the features associated to the current example.",
"score_diff = ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff",
"best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff ) # To be JSON-serializable. if score_diff",
"score that is less than the score of the null answer minus this",
"v in pred.items() } for pred in predictions ] # If we have",
") # Let's loop over all the examples! for example_index, example in enumerate(tqdm(examples)):",
"start_logits[0] + end_logits[0] if ( min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score ):",
"If provided, the dictionaries of predictions, n_best predictions (with their scores and logits)",
"their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this process is the",
"The HuggingFace Team All rights reserved. # # Licensed under the Apache License,",
"corresponding features. example_id_to_index = {k: i for i, k in enumerate(examples[\"id\"])} features_per_example =",
"already exists and is not empty. \" \"Use --overwrite_output_dir to overcome.\" ) elif",
"np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist() for start_index in start_indexes: for end_index",
"have a fast tokenizer. Checkout the big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable",
"( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\":",
"\"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\" ) # Tokenizer check:",
"and end logits. start_indexes = np.argsort(start_logits)[ -1 : -consider - 1 : -1",
"(see the main script for more information). features: The processed dataset (see the",
"models that only return start and end logits. Args: examples: The non-preprocessed dataset",
"{ \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go",
"in `output_dir`. prefix (:obj:`str`, `optional`): If provided, the dictionaries mentioned above are saved",
"not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we first need to find",
"best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable by casting np.float back to",
"assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if",
"f\"Got {len(predictions[0])} predictions and {len(features)} features.\" # Build a map example to its",
"us to map some the positions in our logits to span of texts",
"to answers that are substrings of the original contexts. This is the base",
"pred[\"probability\"] = prob # Pick the best prediction. If the null answer is",
"assert len(predictions[0]) == len( features ), f\"Got {len(predictions[0])} predictions and {len(features)} features.\" #",
"from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\",",
"KIND, either express or implied. # See the License for the specific language",
"as np from tqdm.auto import tqdm from konlpy.tag import Mecab import torch import",
"{len(examples)} example predictions split into {len(features)} features.\" ) # Let's loop over all",
"= False, n_best_size: int = 20, max_answer_length: int = 30, null_score_diff_threshold: float =",
"of its low score. if version_2_with_negative and not any( p[\"offsets\"] == (0, 0)",
"is not None and not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word",
"scratch.\" ) # Tokenizer check: this script requires a fast tokenizer. if not",
"if version_2_with_negative: # Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] #",
"feature_null_score ): min_null_prediction = { \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\":",
"= { \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } #",
"return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function for reproducible behavior to set",
"must be aligned on the fact they `want` to predict a null answer).",
"maximum context # available in the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None",
"stay independent from torch/tf in this file, using # the LogSumExp trick). scores",
"not conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The threshold",
"ANY KIND, either express or implied. # See the License for the specific",
"minimum of the scores for the null answer on each feature: all features",
"and, if :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null",
"= example[\"context\"] for pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] :",
"the model: two arrays containing the start logits and the end logits respectively.",
"start_index or end_index - start_index + 1 > max_answer_length ): continue # Don't",
"if provided we will remove answers that do not have the maximum context",
"for k, v in pred.items() } for pred in predictions ] # If",
"conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The threshold used",
"if ban_word in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append(",
"easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we first need",
"= ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff )",
"None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir)",
"with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"we will remove answers that do not have the maximum context # available",
"= collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have",
"from tqdm.auto import tqdm from konlpy.tag import Mecab import torch import random from",
"prefix is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\"",
"(:obj:`float`, `optional`, defaults to 0): The threshold used to select the null answer:",
") if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix is None else",
"If provided, the dictionaries mentioned above are saved with `prefix` added to their",
"max_answer_length: int = 30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str] = None, prefix:",
"version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json, )",
"= None, is_world_process_zero: bool = True, consider=20 ): \"\"\" Post-processes the predictions of",
"feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go through all possibilities for the",
"removed because of its low score. if version_2_with_negative and not any( p[\"offsets\"] ==",
"if len(predictions) == 0 or ( len(predictions) == 1 and predictions[0][\"text\"] == \"\"",
") if version_2_with_negative: # Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"]",
"mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function for reproducible",
"+= 1 best_non_null_pred = predictions[i] # Then we compare to the null prediction",
"for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to fill.",
"is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we first",
":obj:`True`): Whether this process is the main process or not (used to determine",
")[:n_best_size] # Add back the minimum null prediction if it was removed because",
"n_best predictions (with their scores and logits) and, if :obj:`version_2_with_negative=True`, the dictionary of",
"predictions): pred[\"probability\"] = prob # Pick the best prediction. If the null answer",
"dictionaries mentioned above are saved with `prefix` added to their names. is_world_process_zero (:obj:`bool`,",
"f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix is None",
"\"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args, data_args,",
"ban_words: if ban_word in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word)",
"the base postprocessing functions for models that only return start and end logits.",
"using the threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]]",
"output_dir, \"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\")",
"min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = { \"offsets\": (0,",
"seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The",
"text in the original context. context = example[\"context\"] for pred in predictions: offsets",
"isinstance(v, (np.float16, np.float32, np.float64)) else v ) for k, v in pred.items() }",
"elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the",
"n_best_size (:obj:`int`, `optional`, defaults to 20): The total number of n-best predictions to",
"a length that is either < 0 or > max_answer_length. if ( end_index",
"best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff ) # To be JSON-serializable.",
"example in enumerate(tqdm(examples)): # Those are the indices of the features associated to",
"pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge case",
"probs = exp_scores / exp_scores.sum() # Include the probabilities in our predictions. for",
"len(predictions) == 0 or ( len(predictions) == 1 and predictions[0][\"text\"] == \"\" ):",
"offsets to gather the answer text in the original context. context = example[\"context\"]",
"reverse=True )[:n_best_size] # Add back the minimum null prediction if it was removed",
"or end_index >= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is None ):",
"} ) if version_2_with_negative: # Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score =",
"function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or",
"Pre-processing Post-processing utilities for question answering. \"\"\" import collections import json import logging",
"to generate when looking for an answer. max_answer_length (:obj:`int`, `optional`, defaults to 30):",
"the threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] =",
"k, v in pred.items() } for pred in predictions ] # If we",
"= False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False,",
"offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], }",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the",
"not possible, this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: #",
"low score. if version_2_with_negative and not any( p[\"offsets\"] == (0, 0) for p",
"not have the maximum context # available in the current feature. token_is_max_context =",
"if the best answer has a score that is less than the score",
"None: assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\"",
"True, consider=20 ): \"\"\" Post-processes the predictions of a question-answering model to convert",
"as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file,",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"prelim_predictions = [] # Looping through all the features associated to the current",
"single non-null prediction, we create a fake prediction to avoid # failure. if",
"the null answer: if the best answer has a score that is less",
"writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets):",
"= predictions[i] # Then we compare to the null prediction using the threshold.",
"data_args, tokenizer, datasets): # Detecting last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir)",
"applicable law or agreed to in writing, software # distributed under the License",
"governing permissions and # limitations under the License. \"\"\" Pre-processing Post-processing utilities for",
"set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed",
"import torch import random from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint",
"is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark =",
"scores and logits) and, if :obj:`version_2_with_negative=True`, the dictionary of the scores differences between",
"None ): continue # Don't consider answers with a length that is either",
"pred in zip(probs, predictions): pred[\"probability\"] = prob # Pick the best prediction. If",
"(used to determine if logging/saves should be done). \"\"\" assert ( len(predictions) ==",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"All rights reserved. # # Licensed under the Apache License, Version 2.0 (the",
"dataset (see the main script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions",
"1 and predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\":",
"all the examples! for example_index, example in enumerate(tqdm(examples)): # Those are the indices",
"main script for more information). features: The processed dataset (see the main script",
"pred in predictions]) exp_scores = np.exp(scores - np.max(scores)) probs = exp_scores / exp_scores.sum()",
"LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred in predictions]) exp_scores = np.exp(scores -",
"0 or ( len(predictions) == 1 and predictions[0][\"text\"] == \"\" ): predictions.insert( 0,",
"needed because the start and end predictions are not conditioned on one another.",
"score_diff ) # To be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\"",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"\"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json,",
"`--output_dir` or add `--overwrite_output_dir` to train from scratch.\" ) # Tokenizer check: this",
"training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:",
"not a single non-null prediction, we create a fake prediction to avoid #",
"len(predictions[0]) == len( features ), f\"Got {len(predictions[0])} predictions and {len(features)} features.\" # Build",
"answers that are substrings of the original contexts. This is the base postprocessing",
"to find the model types that meet this \" \"requirement\" ) if data_args.max_seq_length",
"a question-answering model to convert them to answers that are substrings of the",
"{ \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\":",
"compliance with the License. # You may obtain a copy of the License",
"example. for feature_index in feature_indices: # We grab the predictions of the model",
"if version_2_with_negative and not any( p[\"offsets\"] == (0, 0) for p in predictions",
"in our predictions. for prob, pred in zip(probs, predictions): pred[\"probability\"] = prob #",
"start_logits[0], \"end_logit\": end_logits[0], } # Go through all possibilities for the `n_best_size` greater",
"to 0): The threshold used to select the null answer: if the best",
"-1].tolist() for start_index in start_indexes: for end_index in end_indexes: # Don't consider out-of-scope",
"defaults to 20): The total number of n-best predictions to generate when looking",
"a score that is less than the score of the null answer minus",
"don't have the maximum context available (if such information is # provided). if",
"scores (we do it with numpy to stay independent from torch/tf in this",
"consider answer that don't have the maximum context available (if such information is",
"for this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what",
"postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size: int =",
"version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the underlying dataset contains",
"first need to find the best non-empty prediction. i = 0 while predictions[i][\"text\"]",
"If we have an output_dir, let's save all those dicts. if output_dir is",
"this process is the main process or not (used to determine if logging/saves",
"the positions in our logits to span of texts in the original #",
"find the best non-empty prediction. i = 0 while predictions[i][\"text\"] == \"\": i",
"`output_dir`. prefix (:obj:`str`, `optional`): If provided, the dictionaries mentioned above are saved with",
"this example (note that the score of the null answer for an example",
"for the `n_best_size` greater start and end logits. start_indexes = np.argsort(start_logits)[ -1 :",
"\"end_logit\": end_logits[end_index], } ) if version_2_with_negative: # Add the minimum null prediction prelim_predictions.append(min_null_prediction)",
"0.0} ) # Compute the softmax of all scores (we do it with",
"logits to span of texts in the original # context. offset_mapping = features[feature_index][\"offset_mapping\"]",
"provided we will remove answers that do not have the maximum context #",
"`n_best_size` greater start and end logits. start_indexes = np.argsort(start_logits)[ -1 : -consider -",
"select the null answer: if the best answer has a score that is",
"Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split into",
"not a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix is None else",
"non-preprocessed dataset (see the main script for more information). features: The processed dataset",
"Use the offsets to gather the answer text in the original context. context",
"open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\")",
"is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory ({training_args.output_dir}) already exists",
"= collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example",
"isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script only works for models that have",
"): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} ) #",
"# available in the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) #",
"(the \"License\"); # you may not use this file except in compliance with",
"example predictions split into {len(features)} features.\" ) # Let's loop over all the",
"flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\":",
"# Unless required by applicable law or agreed to in writing, software #",
"minimum null prediction if it was removed because of its low score. if",
"by applicable law or agreed to in writing, software # distributed under the",
"is_world_process_zero: bool = True, consider=20 ): \"\"\" Post-processes the predictions of a question-answering",
"`optional`, defaults to 30): The maximum length of an answer that can be",
"for end_index in end_indexes: # Don't consider out-of-scope answers, either because the indices",
"or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = { \"offsets\": (0, 0), \"score\": feature_null_score,",
"= 0 while predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred = predictions[i] #",
"detected, resuming training at {last_checkpoint}. To avoid this behavior, change \" \"the `--output_dir`",
"from typing import Optional, Tuple import numpy as np from tqdm.auto import tqdm",
"file except in compliance with the License. # You may obtain a copy",
"\" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is",
"and {len(features)} features.\" # Build a map example to its corresponding features. example_id_to_index",
"Add back the minimum null prediction if it was removed because of its",
"the big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the model types",
"in start_indexes: for end_index in end_indexes: # Don't consider out-of-scope answers, either because",
"positions in our logits to span of texts in the original # context.",
"exp_scores.sum() # Include the probabilities in our predictions. for prob, pred in zip(probs,",
"We grab the predictions of the model for this feature. start_logits = all_start_logits[feature_index]",
"for question answering. \"\"\" import collections import json import logging import os from",
") for k, v in pred.items() } for pred in predictions ] #",
"used to select the null answer: if the best answer has a score",
"total number of n-best predictions to generate when looking for an answer. max_answer_length",
"less than the score of the null answer minus this threshold, the null",
"features. example_id_to_index = {k: i for i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list)",
"available in the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) # Update",
"all_start_logits, all_end_logits = predictions assert len(predictions[0]) == len( features ), f\"Got {len(predictions[0])} predictions",
"scores differences between best and null answers, are saved in `output_dir`. prefix (:obj:`str`,",
"0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} ) # Compute the",
"nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json, ) if",
"and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is",
"min_null_prediction = { \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], }",
"all_end_logits[feature_index] # This is what will allow us to map some the positions",
"example_index, example in enumerate(tqdm(examples)): # Those are the indices of the features associated",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"end_logits = all_end_logits[feature_index] # This is what will allow us to map some",
"predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the",
"i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to fill. all_predictions",
"token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) # Update minimum null prediction. feature_null_score =",
"flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word in candidate_word: flag=True break if",
"and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir))",
"`optional`, defaults to :obj:`False`): Whether or not the underlying dataset contains examples with",
"writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with",
"None and not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words:",
"determine if logging/saves should be done). \"\"\" assert ( len(predictions) == 2 ),",
"specific language governing permissions and # limitations under the License. \"\"\" Pre-processing Post-processing",
"arrays containing the start logits and the end logits respectively. Its first dimension",
"prediction. If the null answer is not possible, this is easy. if not",
"if prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file,",
"start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index]",
"and is not empty. \" \"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint is",
"prob # Pick the best prediction. If the null answer is not possible,",
"mentioned above are saved with `prefix` added to their names. is_world_process_zero (:obj:`bool`, `optional`,",
"the null answer is not possible, this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]]",
"else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None else",
"else: # Otherwise we first need to find the best non-empty prediction. i",
"= None prelim_predictions = [] # Looping through all the features associated to",
"current example. for feature_index in feature_indices: # We grab the predictions of the",
"last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir",
"x: x[\"score\"], reverse=True )[:n_best_size] # Add back the minimum null prediction if it",
"the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not",
"Go through all possibilities for the `n_best_size` greater start and end logits. start_indexes",
"for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model: two arrays",
"# This is what will allow us to map some the positions in",
"candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word in candidate_word: flag=True break if flag:",
"two arrays containing the start logits and the end logits respectively. Its first",
"because the indices are out of bounds or correspond # to part of",
"we have an output_dir, let's save all those dicts. if output_dir is not",
"The threshold used to select the null answer: if the best answer has",
"max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative: # Add the minimum",
"main script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model:",
"predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} ) # Compute",
"and the end logits respectively. Its first dimension must match the number of",
"(0, 0) for p in predictions ): predictions.append(min_null_prediction) # Use the offsets to",
"p[\"offsets\"] == (0, 0) for p in predictions ): predictions.append(min_null_prediction) # Use the",
"predictions.append(min_null_prediction) # Use the offsets to gather the answer text in the original",
"np.ndarray]`): The predictions of the model: two arrays containing the start logits and",
"Whether this process is the main process or not (used to determine if",
"to {prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving",
"logits respectively. Its first dimension must match the number of elements of :obj:`features`.",
"\"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def",
"answer has a score that is less than the score of the null",
"for the specific language governing permissions and # limitations under the License. \"\"\"",
"last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory ({training_args.output_dir}) already",
"is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this process is the main process",
"# Looping through all the features associated to the current example. for feature_index",
"- start_index + 1 > max_answer_length ): continue # Don't consider answer that",
"end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0]) == len( features ), f\"Got {len(predictions[0])}",
"that are not in the context. if ( start_index >= len(offset_mapping) or end_index",
"examples! for example_index, example in enumerate(tqdm(examples)): # Those are the indices of the",
"Mecab() def tokenize(text): # return text.split(\" \") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x))",
"\"validation\" not in datasets: raise ValueError(\"--do_eval requires a validation dataset\") return last_checkpoint, max_seq_length",
"of the null answer for an example giving several features is the minimum",
"a fast tokenizer. Checkout the big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to",
"prediction to avoid # failure. if len(predictions) == 0 or ( len(predictions) ==",
"to :obj:`False`): Whether or not the underlying dataset contains examples with no answers.",
"of a question-answering model to convert them to answers that are substrings of",
"logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) +",
"texts in the original # context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if",
"Otherwise we first need to find the best non-empty prediction. i = 0",
"predictions to {prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\")",
"be a tuple with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert",
"are saved with `prefix` added to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to",
"is not empty. \" \"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint is not",
"predictions[0][\"text\"] else: # Otherwise we first need to find the best non-empty prediction.",
"context available (if such information is # provided). if ( token_is_max_context is not",
"= os.path.join( output_dir, \"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions",
"as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\")",
"`token_is_max_context`, if provided we will remove answers that do not have the maximum",
") elif last_checkpoint is not None: logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}.",
"f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change \" \"the",
"i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i)",
"has a score that is less than the score of the null answer",
"# coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved. # #",
"to 30): The maximum length of an answer that can be generated. This",
"int): \"\"\" Helper function for reproducible behavior to set the seed in ``random``,",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"null answer is selected for this example (note that the score of the",
"script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model: two",
"writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file,",
"os.path.join( output_dir, \"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to",
"best `n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] #",
"non-null prediction, we create a fake prediction to avoid # failure. if len(predictions)",
"trick). scores = np.array([pred.pop(\"score\") for pred in predictions]) exp_scores = np.exp(scores - np.max(scores))",
"is None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix is",
"== \"\": i += 1 best_non_null_pred = predictions[i] # Then we compare to",
"is less than the score of the null answer minus this threshold, the",
"of the model: two arrays containing the start logits and the end logits",
"are substrings of the original contexts. This is the base postprocessing functions for",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge",
"1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function for reproducible behavior to set the",
"to span of texts in the original # context. offset_mapping = features[feature_index][\"offset_mapping\"] #",
"# the LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred in predictions]) exp_scores =",
"bool = True, consider=20 ): \"\"\" Post-processes the predictions of a question-answering model",
"in our logits to span of texts in the original # context. offset_mapping",
"in the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) # Update minimum",
"/ exp_scores.sum() # Include the probabilities in our predictions. for prob, pred in",
"prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep the best `n_best_size` predictions. predictions",
"\"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text): # return text.split(\" \") return mecab.morphs(text)",
"Tokenizer check: this script requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise",
"each feature: all features must be aligned on the fact they `want` to",
"that can be generated. This is needed because the start and end predictions",
"= best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable by casting np.float back",
"script requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example",
"a single non-null prediction, we create a fake prediction to avoid # failure.",
"model for this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is",
"the best `n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size]",
"is the main process or not (used to determine if logging/saves should be",
"else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable by casting",
"# Don't consider answers with a length that is either < 0 or",
"the predictions of a question-answering model to convert them to answers that are",
"done). \"\"\" assert ( len(predictions) == 2 ), \"`predictions` should be a tuple",
"defaults to 30): The maximum length of an answer that can be generated.",
"1 best_non_null_pred = predictions[i] # Then we compare to the null prediction using",
"# Add back the minimum null prediction if it was removed because of",
"find the model types that meet this \" \"requirement\" ) if data_args.max_seq_length >",
"logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) +",
"information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model: two arrays containing the",
"== len( features ), f\"Got {len(predictions[0])} predictions and {len(features)} features.\" # Build a",
"when looking for an answer. max_answer_length (:obj:`int`, `optional`, defaults to 30): The maximum",
"is None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = { \"offsets\": (0, 0),",
"rights reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"to find the best non-empty prediction. i = 0 while predictions[i][\"text\"] == \"\":",
"indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\")",
"the specific language governing permissions and # limitations under the License. \"\"\" Pre-processing",
"the main script for more information). features: The processed dataset (see the main",
"the License for the specific language governing permissions and # limitations under the",
"null answer on each feature: all features must be aligned on the fact",
"script only works for models that have a fast tokenizer. Checkout the big",
"feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to fill. all_predictions =",
"grab the predictions of the model for this feature. start_logits = all_start_logits[feature_index] end_logits",
"the scores for the null answer on each feature: all features must be",
"version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False)",
"if logging/saves should be done). \"\"\" assert ( len(predictions) == 2 ), \"`predictions`",
"ban_word in ban_words: if ban_word in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue",
"= min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets: raise ValueError(\"--do_eval requires a validation",
"threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float(",
"in predictions ] # If we have an output_dir, let's save all those",
"the score of the null answer minus this threshold, the null answer is",
"Detecting last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not",
"scores_diff_json[example[\"id\"]] = float( score_diff ) # To be JSON-serializable. if score_diff > null_score_diff_threshold:",
"all the features associated to the current example. for feature_index in feature_indices: #",
"predictions are not conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0):",
"predictions ] # If we have an output_dir, let's save all those dicts.",
"to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return",
"offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge case we have not a",
"the null prediction using the threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"] -",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"example. feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions = [] # Looping through",
"in zip(probs, predictions): pred[\"probability\"] = prob # Pick the best prediction. If the",
"do not have the maximum context # available in the current feature. token_is_max_context",
"elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0]) == len( features ),",
"add `--overwrite_output_dir` to train from scratch.\" ) # Tokenizer check: this script requires",
"<filename>MRC/utils_qa.py # coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved. #",
"if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we first need to",
"indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as writer:",
":obj:`False`): Whether or not the underlying dataset contains examples with no answers. n_best_size",
"logits) and, if :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and",
"as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer,",
"context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we will remove answers",
"np.exp(scores - np.max(scores)) probs = exp_scores / exp_scores.sum() # Include the probabilities in",
"= np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist() for start_index in start_indexes: for",
"non-empty prediction. i = 0 while predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred",
"20, max_answer_length: int = 30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str] = None,",
"answer is selected for this example (note that the score of the null",
"= collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else",
"because of its low score. if version_2_with_negative and not any( p[\"offsets\"] == (0,",
"the current example. feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions = [] #",
"Tuple import numpy as np from tqdm.auto import tqdm from konlpy.tag import Mecab",
"len( features ), f\"Got {len(predictions[0])} predictions and {len(features)} features.\" # Build a map",
"k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) #",
"null answer is not possible, this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] =",
"maximum length of an answer that can be generated. This is needed because",
"--overwrite_output_dir to overcome.\" ) elif last_checkpoint is not None: logger.info( f\"Checkpoint detected, resuming",
"have the maximum context # available in the current feature. token_is_max_context = features[feature_index].get(",
"the number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"answer on each feature: all features must be aligned on the fact they",
"2 ), \"`predictions` should be a tuple with two elements (start_logits, end_logits).\" all_start_logits,",
"on the fact they `want` to predict a null answer). Only useful when",
"logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split into {len(features)} features.\" ) # Let's",
"= context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge case we",
"``tf`` (if installed). Args: seed (:obj:`int`): The seed to set. \"\"\" random.seed(seed) np.random.seed(seed)",
"# Include the probabilities in our predictions. for prob, pred in zip(probs, predictions):",
"# Compute the softmax of all scores (we do it with numpy to",
"logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\",",
"is not a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix is None",
"writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as",
"checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ):",
"underlying dataset contains examples with no answers. n_best_size (:obj:`int`, `optional`, defaults to 20):",
"-consider - 1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider - 1",
"or correspond # to part of the input_ids that are not in the",
"(:obj:`str`, `optional`): If provided, the dictionaries mentioned above are saved with `prefix` added",
"minimum null prediction. feature_null_score = start_logits[0] + end_logits[0] if ( min_null_prediction is None",
"( len(predictions) == 1 and predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\": \"empty\",",
"if it was removed because of its low score. if version_2_with_negative and not",
"predictions ): predictions.append(min_null_prediction) # Use the offsets to gather the answer text in",
"\"`predictions` should be a tuple with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits =",
"data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum",
"= 20, max_answer_length: int = 30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str] =",
"fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() #",
"0) for p in predictions ): predictions.append(min_null_prediction) # Use the offsets to gather",
"into {len(features)} features.\" ) # Let's loop over all the examples! for example_index,",
"if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info(",
"behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed).",
"None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and",
"save all those dicts. if output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir} is",
"a fake prediction to avoid # failure. if len(predictions) == 0 or (",
"logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change \"",
"to convert them to answers that are substrings of the original contexts. This",
"no answers. n_best_size (:obj:`int`, `optional`, defaults to 20): The total number of n-best",
"token_is_max_context is not None and not token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for",
"is not None: assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file = os.path.join(",
"for pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"])",
") # To be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else:",
"raise ValueError( \"This example script only works for models that have a fast",
"for pred in predictions]) exp_scores = np.exp(scores - np.max(scores)) probs = exp_scores /",
"more information). features: The processed dataset (see the main script for more information).",
"-consider - 1 : -1].tolist() for start_index in start_indexes: for end_index in end_indexes:",
"\"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with",
"), \"`predictions` should be a tuple with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits",
"continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word in candidate_word: flag=True break",
"In the very rare edge case we have not a single non-null prediction,",
"\" \"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint is not None: logger.info( f\"Checkpoint",
"logging import os from typing import Optional, Tuple import numpy as np from",
"import numpy as np from tqdm.auto import tqdm from konlpy.tag import Mecab import",
":obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the underlying dataset",
"Don't consider answer that don't have the maximum context available (if such information",
"len(predictions) == 2 ), \"`predictions` should be a tuple with two elements (start_logits,",
"= {k: i for i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i,",
"change \" \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\" ) #",
"max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the\" f\"model ({tokenizer.model_max_length}).",
"predictions]) exp_scores = np.exp(scores - np.max(scores)) probs = exp_scores / exp_scores.sum() # Include",
"the best prediction. If the null answer is not possible, this is easy.",
"answer: if the best answer has a score that is less than the",
"Optional[str] = None, prefix: Optional[str] = None, is_world_process_zero: bool = True, consider=20 ):",
"= best_non_null_pred # Make `predictions` JSON-serializable by casting np.float back to float. all_nbest_json[example[\"id\"]]",
"ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as",
"the minimum of the scores for the null answer on each feature: all",
"if version_2_with_negative: logger.info(f\"Saving null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4,",
"konlpy.tag import Mecab import torch import random from transformers import is_torch_available, PreTrainedTokenizerFast from",
"current example. feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions = [] # Looping",
"context. if ( start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is",
"avoid this behavior, change \" \"the `--output_dir` or add `--overwrite_output_dir` to train from",
"continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\":",
"break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1],",
"= exp_scores / exp_scores.sum() # Include the probabilities in our predictions. for prob,",
"reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"{k: i for i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature",
"-1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist() for start_index",
"an answer that can be generated. This is needed because the start and",
"with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to",
"predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size: int = 20, max_answer_length: int",
"in predictions]) exp_scores = np.exp(scores - np.max(scores)) probs = exp_scores / exp_scores.sum() #",
"elif last_checkpoint is not None: logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}. To",
"if ( token_is_max_context is not None and not token_is_max_context.get(str(start_index), False) ): continue flag=False",
"logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) +",
"for the null answer on each feature: all features must be aligned on",
"that only return start and end logits. Args: examples: The non-preprocessed dataset (see",
"exp_scores = np.exp(scores - np.max(scores)) probs = exp_scores / exp_scores.sum() # Include the",
"\"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False)",
"OF ANY KIND, either express or implied. # See the License for the",
"score. if version_2_with_negative and not any( p[\"offsets\"] == (0, 0) for p in",
"larger than the maximum length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length",
"# In the very rare edge case we have not a single non-null",
"indices of the features associated to the current example. feature_indices = features_per_example[example_index] min_null_prediction",
"Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets: raise",
"while predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred = predictions[i] # Then we",
"version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else: # Otherwise we first need to find the",
"be done). \"\"\" assert ( len(predictions) == 2 ), \"`predictions` should be a",
"collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions",
"dataset contains examples with no answers. n_best_size (:obj:`int`, `optional`, defaults to 20): The",
"indices are out of bounds or correspond # to part of the input_ids",
"\"end_logit\": 0.0, \"score\": 0.0} ) # Compute the softmax of all scores (we",
") # Update minimum null prediction. feature_null_score = start_logits[0] + end_logits[0] if (",
"empty. \" \"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint is not None: logger.info(",
"all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last checkpoint. last_checkpoint = None",
"predictions split into {len(features)} features.\" ) # Let's loop over all the examples!",
"the License. \"\"\" Pre-processing Post-processing utilities for question answering. \"\"\" import collections import",
"import random from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger =",
"not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) >",
"if ( min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = {",
"PreTrainedTokenizerFast): raise ValueError( \"This example script only works for models that have a",
"to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this process is",
"( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff ) #",
"the main process or not (used to determine if logging/saves should be done).",
"null prediction. feature_null_score = start_logits[0] + end_logits[0] if ( min_null_prediction is None or",
"f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json,",
"https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this \" \"requirement\" ) if",
"prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0),",
"= sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add back the minimum",
"the start logits and the end logits respectively. Its first dimension must match",
"def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last checkpoint. last_checkpoint = None if",
"original context. context = example[\"context\"] for pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"]",
"= 0.0, output_dir: Optional[str] = None, prefix: Optional[str] = None, is_world_process_zero: bool =",
"import collections import json import logging import os from typing import Optional, Tuple",
") logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False)",
"-1 : -consider - 1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider",
"that the score of the null answer for an example giving several features",
"== \"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0}",
"False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word in candidate_word:",
"# Pick the best prediction. If the null answer is not possible, this",
"not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script only works for models that",
"provided, the dictionaries mentioned above are saved with `prefix` added to their names.",
"\"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text): # return text.split(\" \") return",
"feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what will allow",
"else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions,",
"do it with numpy to stay independent from torch/tf in this file, using",
"fast tokenizer. Checkout the big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find",
"{\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} ) # Compute the softmax",
"or agreed to in writing, software # distributed under the License is distributed",
"of the input_ids that are not in the context. if ( start_index >=",
"return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last checkpoint. last_checkpoint =",
"this script requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This",
"all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging.",
"prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\")",
"# Let's loop over all the examples! for example_index, example in enumerate(tqdm(examples)): #",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split into {len(features)} features.\" ) #",
"have an output_dir, let's save all those dicts. if output_dir is not None:",
"generate when looking for an answer. max_answer_length (:obj:`int`, `optional`, defaults to 30): The",
"License. # You may obtain a copy of the License at # #",
"to fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict()",
"the main script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the",
"question-answering model to convert them to answers that are substrings of the original",
"in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\":",
"# Tokenizer check: this script requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast):",
"in this file, using # the LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred",
"None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\") as writer:",
"those dicts. if output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir} is not a",
"to its corresponding features. example_id_to_index = {k: i for i, k in enumerate(examples[\"id\"])}",
"either because the indices are out of bounds or correspond # to part",
"\"\"\" Post-processes the predictions of a question-answering model to convert them to answers",
"threshold used to select the null answer: if the best answer has a",
"if :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null answers,",
"0 or > max_answer_length. if ( end_index < start_index or end_index - start_index",
"To avoid this behavior, change \" \"the `--output_dir` or add `--overwrite_output_dir` to train",
"or > max_answer_length. if ( end_index < start_index or end_index - start_index +",
"# To be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]]",
"and end predictions are not conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults",
"maximum length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)",
"): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word in candidate_word: flag=True",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"are out of bounds or correspond # to part of the input_ids that",
"seed (:obj:`int`): The seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed)",
"float = 0.0, output_dir: Optional[str] = None, prefix: Optional[str] = None, is_world_process_zero: bool",
"that do not have the maximum context # available in the current feature.",
"json import logging import os from typing import Optional, Tuple import numpy as",
"match the number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`):",
"mecab = Mecab() def tokenize(text): # return text.split(\" \") return mecab.morphs(text) def sigmoid(x):",
"+ \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4,",
"np.float64)) else v ) for k, v in pred.items() } for pred in",
"that meet this \" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length",
"end_logits[0] if ( min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction =",
"last_checkpoint is not None: logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid",
"answer minus this threshold, the null answer is selected for this example (note",
"logger.info( f\"Post-processing {len(examples)} example predictions split into {len(features)} features.\" ) # Let's loop",
"predictions assert len(predictions[0]) == len( features ), f\"Got {len(predictions[0])} predictions and {len(features)} features.\"",
"end_indexes = np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist() for start_index in start_indexes:",
"permissions and # limitations under the License. \"\"\" Pre-processing Post-processing utilities for question",
"Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch``",
"defaults to :obj:`False`): Whether or not the underlying dataset contains examples with no",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"(np.float16, np.float32, np.float64)) else v ) for k, v in pred.items() } for",
"seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if",
"last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError(",
"> 0: raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not empty.",
"end_index >= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is None ): continue",
"not None: logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior,",
"Update minimum null prediction. feature_null_score = start_logits[0] + end_logits[0] if ( min_null_prediction is",
"compare to the null prediction using the threshold. score_diff = ( null_score -",
"score of the null answer minus this threshold, the null answer is selected",
"\"\"\" Helper function for reproducible behavior to set the seed in ``random``, ``numpy``,",
"null answer for an example giving several features is the minimum of the",
"features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we will remove answers that do not",
"= True, consider=20 ): \"\"\" Post-processes the predictions of a question-answering model to",
"end logits respectively. Its first dimension must match the number of elements of",
"to the current example. feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions = []",
"if prefix is None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if",
"information is # provided). if ( token_is_max_context is not None and not token_is_max_context.get(str(start_index),",
"Only keep the best `n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"],",
"os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is",
"# if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples,",
"tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script only works for",
"\"아무래도\") mecab = Mecab() def tokenize(text): # return text.split(\" \") return mecab.morphs(text) def",
"set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU",
"tokenizer.model_max_length) if \"validation\" not in datasets: raise ValueError(\"--do_eval requires a validation dataset\") return",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"The total number of n-best predictions to generate when looking for an answer.",
"that is less than the score of the null answer minus this threshold,",
"and # limitations under the License. \"\"\" Pre-processing Post-processing utilities for question answering.",
"giving several features is the minimum of the scores for the null answer",
"the indices are out of bounds or correspond # to part of the",
"0.0, output_dir: Optional[str] = None, prefix: Optional[str] = None, is_world_process_zero: bool = True,",
"scores = np.array([pred.pop(\"score\") for pred in predictions]) exp_scores = np.exp(scores - np.max(scores)) probs",
"( float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v ) for k, v",
"open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds",
"# limitations under the License. \"\"\" Pre-processing Post-processing utilities for question answering. \"\"\"",
"for this example (note that the score of the null answer for an",
"out-of-scope answers, either because the indices are out of bounds or correspond #",
"process is the main process or not (used to determine if logging/saves should",
"very rare edge case we have not a single non-null prediction, we create",
") scores_diff_json[example[\"id\"]] = float( score_diff ) # To be JSON-serializable. if score_diff >",
"is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\") as",
"collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if",
"that are substrings of the original contexts. This is the base postprocessing functions",
"\"token_is_max_context\", None ) # Update minimum null prediction. feature_null_score = start_logits[0] + end_logits[0]",
"of an answer that can be generated. This is needed because the start",
"is needed because the start and end predictions are not conditioned on one",
"using # the LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred in predictions]) exp_scores",
"or implied. # See the License for the specific language governing permissions and",
"is either < 0 or > max_answer_length. if ( end_index < start_index or",
"0: raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not empty. \"",
"predictions and {len(features)} features.\" # Build a map example to its corresponding features.",
"start and end predictions are not conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`,",
"all_end_logits = predictions assert len(predictions[0]) == len( features ), f\"Got {len(predictions[0])} predictions and",
"max_answer_length. if ( end_index < start_index or end_index - start_index + 1 >",
"dicts. if output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\"",
"zip(probs, predictions): pred[\"probability\"] = prob # Pick the best prediction. If the null",
"if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split into {len(features)} features.\"",
"start_indexes = np.argsort(start_logits)[ -1 : -consider - 1 : -1 ].tolist() end_indexes =",
"of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the underlying",
"torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def",
"null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix is None else f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving",
"collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN)",
"i = 0 while predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred = predictions[i]",
"a null answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If",
": -1].tolist() for start_index in start_indexes: for end_index in end_indexes: # Don't consider",
"feature: all features must be aligned on the fact they `want` to predict",
"flag=True break if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0],",
"is selected for this example (note that the score of the null answer",
"all scores (we do it with numpy to stay independent from torch/tf in",
"loop over all the examples! for example_index, example in enumerate(tqdm(examples)): # Those are",
"the answer text in the original context. context = example[\"context\"] for pred in",
"start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative: # Add the minimum null prediction",
"not (used to determine if logging/saves should be done). \"\"\" assert ( len(predictions)",
"of predictions, n_best predictions (with their scores and logits) and, if :obj:`version_2_with_negative=True`, the",
"of the scores for the null answer on each feature: all features must",
"or not the underlying dataset contains examples with no answers. n_best_size (:obj:`int`, `optional`,",
"resuming training at {last_checkpoint}. To avoid this behavior, change \" \"the `--output_dir` or",
"start_index + 1 > max_answer_length ): continue # Don't consider answer that don't",
"through all the features associated to the current example. for feature_index in feature_indices:",
"predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0, \"score\":",
"null answer: if the best answer has a score that is less than",
"use this file except in compliance with the License. # You may obtain",
"np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True",
"to train from scratch.\" ) # Tokenizer check: this script requires a fast",
"big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the model types that",
"the score of the null answer for an example giving several features is",
"one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The threshold used to select",
"): continue # Don't consider answers with a length that is either <",
"continue # Don't consider answer that don't have the maximum context available (if",
"last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint",
"= 30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str] = None, prefix: Optional[str] =",
"``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed to set. \"\"\"",
"of the features associated to the current example. feature_indices = features_per_example[example_index] min_null_prediction =",
") if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than",
"Post-processes the predictions of a question-answering model to convert them to answers that",
"len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is None ): continue # Don't",
"keep the best `n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True",
"(if installed). Args: seed (:obj:`int`): The seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if",
"enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries",
"split into {len(features)} features.\" ) # Let's loop over all the examples! for",
"{last_checkpoint}. To avoid this behavior, change \" \"the `--output_dir` or add `--overwrite_output_dir` to",
"Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the dictionaries",
"0 while predictions[i][\"text\"] == \"\": i += 1 best_non_null_pred = predictions[i] # Then",
"} # Go through all possibilities for the `n_best_size` greater start and end",
"is None ): continue # Don't consider answers with a length that is",
"(:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this process is the main process or",
"datasets): # Detecting last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train",
"(:obj:`int`, `optional`, defaults to 20): The total number of n-best predictions to generate",
"open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args,",
"the underlying dataset contains examples with no answers. n_best_size (:obj:`int`, `optional`, defaults to",
"the null answer minus this threshold, the null answer is selected for this",
"differences between best and null answers, are saved in `output_dir`. prefix (:obj:`str`, `optional`):",
"table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet",
"for models that only return start and end logits. Args: examples: The non-preprocessed",
"\"end_logit\": end_logits[0], } # Go through all possibilities for the `n_best_size` greater start",
"types that meet this \" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The",
"0.0, \"score\": 0.0} ) # Compute the softmax of all scores (we do",
"of the null answer minus this threshold, the null answer is selected for",
"to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use",
"# We grab the predictions of the model for this feature. start_logits =",
"with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\") return all_predictions def",
"feature_index in feature_indices: # We grab the predictions of the model for this",
"the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`):",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"contexts. This is the base postprocessing functions for models that only return start",
"Args: seed (:obj:`int`): The seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed)",
"to map some the positions in our logits to span of texts in",
"\"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last checkpoint. last_checkpoint",
"tqdm.auto import tqdm from konlpy.tag import Mecab import torch import random from transformers",
"to gather the answer text in the original context. context = example[\"context\"] for",
"(see the main script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of",
"minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep the best `n_best_size`",
"sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative: # Add",
"The seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) #",
") # Compute the softmax of all scores (we do it with numpy",
"it with numpy to stay independent from torch/tf in this file, using #",
"(:obj:`int`): The seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed)",
":obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the dictionaries of predictions, n_best predictions (with",
"dimension must match the number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"exists and is not empty. \" \"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint",
"pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) #",
"only works for models that have a fast tokenizer. Checkout the big table",
"Post-processing utilities for question answering. \"\"\" import collections import json import logging import",
"have the maximum context available (if such information is # provided). if (",
"provided). if ( token_is_max_context is not None and not token_is_max_context.get(str(start_index), False) ): continue",
"length that is either < 0 or > max_answer_length. if ( end_index <",
"end_index - start_index + 1 > max_answer_length ): continue # Don't consider answer",
"= float( score_diff ) # To be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]]",
"p in predictions ): predictions.append(min_null_prediction) # Use the offsets to gather the answer",
"min_null_prediction[\"score\"] # Only keep the best `n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda",
"process or not (used to determine if logging/saves should be done). \"\"\" assert",
"added to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether this process",
"output_dir (:obj:`str`, `optional`): If provided, the dictionaries of predictions, n_best predictions (with their",
"coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved. # # Licensed",
"with the License. # You may obtain a copy of the License at",
"for an answer. max_answer_length (:obj:`int`, `optional`, defaults to 30): The maximum length of",
"feature_indices: # We grab the predictions of the model for this feature. start_logits",
"2020 The HuggingFace Team All rights reserved. # # Licensed under the Apache",
"+ 1 > max_answer_length ): continue # Don't consider answer that don't have",
"that don't have the maximum context available (if such information is # provided).",
"models that have a fast tokenizer. Checkout the big table of models \"",
"in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to fill. all_predictions = collections.OrderedDict()",
"Pick the best prediction. If the null answer is not possible, this is",
"the maximum context # available in the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\",",
"Copyright 2020 The HuggingFace Team All rights reserved. # # Licensed under the",
"np.array([pred.pop(\"score\") for pred in predictions]) exp_scores = np.exp(scores - np.max(scores)) probs = exp_scores",
": -consider - 1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider -",
"an answer. max_answer_length (:obj:`int`, `optional`, defaults to 30): The maximum length of an",
"random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic =",
"at {last_checkpoint}. To avoid this behavior, change \" \"the `--output_dir` or add `--overwrite_output_dir`",
"law or agreed to in writing, software # distributed under the License is",
"behavior, change \" \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\" )",
"\") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function",
"max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets: raise ValueError(\"--do_eval",
"(:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model: two arrays containing the start logits",
"map some the positions in our logits to span of texts in the",
"20): The total number of n-best predictions to generate when looking for an",
"of n-best predictions to generate when looking for an answer. max_answer_length (:obj:`int`, `optional`,",
"predictions. for prob, pred in zip(probs, predictions): pred[\"probability\"] = prob # Pick the",
"``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed to set.",
"pred.items() } for pred in predictions ] # If we have an output_dir,",
"prefix (:obj:`str`, `optional`): If provided, the dictionaries mentioned above are saved with `prefix`",
"key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add back the minimum null prediction if",
"the predictions of the model for this feature. start_logits = all_start_logits[feature_index] end_logits =",
"in feature_indices: # We grab the predictions of the model for this feature.",
"# to part of the input_ids that are not in the context. if",
"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",
"continue # Don't consider answers with a length that is either < 0",
"# Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split",
"let's save all those dicts. if output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir}",
"`want` to predict a null answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"if isinstance(v, (np.float16, np.float32, np.float64)) else v ) for k, v in pred.items()",
"return start and end logits. Args: examples: The non-preprocessed dataset (see the main",
"= [ { k: ( float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"or ( len(predictions) == 1 and predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\":",
"features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The dictionaries we have to fill. all_predictions = collections.OrderedDict() all_nbest_json =",
"the very rare edge case we have not a single non-null prediction, we",
"to float. all_nbest_json[example[\"id\"]] = [ { k: ( float(v) if isinstance(v, (np.float16, np.float32,",
"output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file =",
"False, n_best_size: int = 20, max_answer_length: int = 30, null_score_diff_threshold: float = 0.0,",
"i += 1 best_non_null_pred = predictions[i] # Then we compare to the null",
"not empty. \" \"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint is not None:",
"version_2_with_negative and not any( p[\"offsets\"] == (0, 0) for p in predictions ):",
"input_ids that are not in the context. if ( start_index >= len(offset_mapping) or",
"The non-preprocessed dataset (see the main script for more information). features: The processed",
"} for pred in predictions ] # If we have an output_dir, let's",
"predictions of the model for this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index]",
"end logits. start_indexes = np.argsort(start_logits)[ -1 : -consider - 1 : -1 ].tolist()",
"Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep the",
"meet this \" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed",
"Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size: int = 20, max_answer_length: int =",
"\"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if version_2_with_negative: logger.info(f\"Saving null_odds to",
"is the minimum of the scores for the null answer on each feature:",
"text.split(\" \") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper",
"to {nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\") if",
"[] # Looping through all the features associated to the current example. for",
"x[\"score\"], reverse=True )[:n_best_size] # Add back the minimum null prediction if it was",
"\"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text): # return text.split(\"",
"through all possibilities for the `n_best_size` greater start and end logits. start_indexes =",
"1 > max_answer_length ): continue # Don't consider answer that don't have the",
"output_dir, \"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir,",
"what will allow us to map some the positions in our logits to",
"Team All rights reserved. # # Licensed under the Apache License, Version 2.0",
"\" \"at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this \" \"requirement\"",
"features ), f\"Got {len(predictions[0])} predictions and {len(features)} features.\" # Build a map example",
"in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature[\"example_id\"]]].append(i) # The",
"are not in the context. if ( start_index >= len(offset_mapping) or end_index >=",
"prefix: Optional[str] = None, is_world_process_zero: bool = True, consider=20 ): \"\"\" Post-processes the",
"- 1 : -1].tolist() for start_index in start_indexes: for end_index in end_indexes: #",
"< start_index or end_index - start_index + 1 > max_answer_length ): continue #",
"(:obj:`str`, `optional`): If provided, the dictionaries of predictions, n_best predictions (with their scores",
"a tuple with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0])",
"\"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text): #",
"for ban_word in ban_words: if ban_word in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word)",
"prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep the best `n_best_size` predictions. predictions =",
"predictions of the model: two arrays containing the start logits and the end",
"fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script only works",
"if output_dir is not None: assert os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file",
"null_odds to {null_odds_file}.\") with open(null_odds_file, \"w\") as writer: writer.write(json.dumps(scores_diff_json, indent=4, ensure_ascii=False) + \"\\n\")",
"and null answers, are saved in `output_dir`. prefix (:obj:`str`, `optional`): If provided, the",
"Its first dimension must match the number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`,",
"best_non_null_pred # Make `predictions` JSON-serializable by casting np.float back to float. all_nbest_json[example[\"id\"]] =",
"feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) # Update minimum null prediction. feature_null_score",
"the minimum null prediction if it was removed because of its low score.",
"else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if prefix is",
"= True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative:",
"# Otherwise we first need to find the best non-empty prediction. i =",
"None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix is None",
"np.float back to float. all_nbest_json[example[\"id\"]] = [ { k: ( float(v) if isinstance(v,",
"example giving several features is the minimum of the scores for the null",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"a map example to its corresponding features. example_id_to_index = {k: i for i,",
"= np.array([pred.pop(\"score\") for pred in predictions]) exp_scores = np.exp(scores - np.max(scores)) probs =",
"available (if such information is # provided). if ( token_is_max_context is not None",
"nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json, indent=4, ensure_ascii=False) + \"\\n\")",
"True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool",
"version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing",
"= all_end_logits[feature_index] # This is what will allow us to map some the",
"can be generated. This is needed because the start and end predictions are",
"is what will allow us to map some the positions in our logits",
"the original # context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we",
"\"start_logit\": 0.0, \"end_logit\": 0.0, \"score\": 0.0} ) # Compute the softmax of all",
"aligned on the fact they `want` to predict a null answer). Only useful",
"< 0 or > max_answer_length. if ( end_index < start_index or end_index -",
"to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args:",
"null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The threshold used to select the null",
"maximum context available (if such information is # provided). if ( token_is_max_context is",
"To be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] =",
"return text.split(\" \") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\"",
"f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in",
"respectively. Its first dimension must match the number of elements of :obj:`features`. version_2_with_negative",
"associated to the current example. feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions =",
"if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script only works for models",
"this file except in compliance with the License. # You may obtain a",
"current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None ) # Update minimum null prediction.",
"Make `predictions` JSON-serializable by casting np.float back to float. all_nbest_json[example[\"id\"]] = [ {",
"will allow us to map some the positions in our logits to span",
"= [] # Looping through all the features associated to the current example.",
"= None, prefix: Optional[str] = None, is_world_process_zero: bool = True, consider=20 ): \"\"\"",
"if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if",
"fake prediction to avoid # failure. if len(predictions) == 0 or ( len(predictions)",
"installed). Args: seed (:obj:`int`): The seed to set. \"\"\" random.seed(seed) np.random.seed(seed) if is_torch_available():",
"i for i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature in",
"This is the base postprocessing functions for models that only return start and",
"predictions. predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add back",
"The processed dataset (see the main script for more information). predictions (:obj:`Tuple[np.ndarray, np.ndarray]`):",
"predictions, n_best predictions (with their scores and logits) and, if :obj:`version_2_with_negative=True`, the dictionary",
"will remove answers that do not have the maximum context # available in",
"of texts in the original # context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`,",
"tuple with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0]) ==",
"best non-empty prediction. i = 0 while predictions[i][\"text\"] == \"\": i += 1",
"minus this threshold, the null answer is selected for this example (note that",
"# Optional `token_is_max_context`, if provided we will remove answers that do not have",
"end predictions are not conditioned on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to",
"sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add back the minimum null",
"= features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we will remove answers that do",
"case we have not a single non-null prediction, we create a fake prediction",
"output_dir: Optional[str] = None, prefix: Optional[str] = None, is_world_process_zero: bool = True, consider=20",
"v ) for k, v in pred.items() } for pred in predictions ]",
"or offset_mapping[start_index] is None or offset_mapping[end_index] is None ): continue # Don't consider",
"bounds or correspond # to part of the input_ids that are not in",
">= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is None ): continue #",
"\"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative: # Add the minimum null",
"predictions (:obj:`Tuple[np.ndarray, np.ndarray]`): The predictions of the model: two arrays containing the start",
"= \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable",
"JSON-serializable by casting np.float back to float. all_nbest_json[example[\"id\"]] = [ { k: (",
"features[feature_index].get( \"token_is_max_context\", None ) # Update minimum null prediction. feature_null_score = start_logits[0] +",
"== 2 ), \"`predictions` should be a tuple with two elements (start_logits, end_logits).\"",
"null answers, are saved in `output_dir`. prefix (:obj:`str`, `optional`): If provided, the dictionaries",
"f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the\" f\"model",
"convert them to answers that are substrings of the original contexts. This is",
"= np.exp(scores - np.max(scores)) probs = exp_scores / exp_scores.sum() # Include the probabilities",
"( len(predictions) == 2 ), \"`predictions` should be a tuple with two elements",
"to the current example. for feature_index in feature_indices: # We grab the predictions",
"not in the context. if ( start_index >= len(offset_mapping) or end_index >= len(offset_mapping)",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file = os.path.join( output_dir, \"null_odds.json\" if",
"in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed",
"tokenizer, datasets): # Detecting last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and",
"rare edge case we have not a single non-null prediction, we create a",
"JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]]",
"\"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger",
"all_nbest_json[example[\"id\"]] = [ { k: ( float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else",
"features associated to the current example. feature_indices = features_per_example[example_index] min_null_prediction = None prelim_predictions",
"if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than the",
"from scratch.\" ) # Tokenizer check: this script requires a fast tokenizer. if",
"dataset (see the main script for more information). features: The processed dataset (see",
"span of texts in the original # context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional",
"min_null_prediction = None prelim_predictions = [] # Looping through all the features associated",
"when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the dictionaries of predictions,",
"required by applicable law or agreed to in writing, software # distributed under",
"return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function for",
"to overcome.\" ) elif last_checkpoint is not None: logger.info( f\"Checkpoint detected, resuming training",
"= None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint =",
"The maximum length of an answer that can be generated. This is needed",
"), f\"Got {len(predictions[0])} predictions and {len(features)} features.\" # Build a map example to",
"for example_index, example in enumerate(tqdm(examples)): # Those are the indices of the features",
"fact they `want` to predict a null answer). Only useful when :obj:`version_2_with_negative` is",
"= features_per_example[example_index] min_null_prediction = None prelim_predictions = [] # Looping through all the",
"\"Use --overwrite_output_dir to overcome.\" ) elif last_checkpoint is not None: logger.info( f\"Checkpoint detected,",
"the features associated to the current example. feature_indices = features_per_example[example_index] min_null_prediction = None",
"several features is the minimum of the scores for the null answer on",
"associated to the current example. for feature_index in feature_indices: # We grab the",
"prediction. feature_null_score = start_logits[0] + end_logits[0] if ( min_null_prediction is None or min_null_prediction[\"score\"]",
"the dictionary of the scores differences between best and null answers, are saved",
": offsets[1]] #print(pred[\"text\"],pred[\"score\"],pred[\"start_logit\"],pred[\"end_logit\"]) # In the very rare edge case we have not",
"the LogSumExp trick). scores = np.array([pred.pop(\"score\") for pred in predictions]) exp_scores = np.exp(scores",
"from konlpy.tag import Mecab import torch import random from transformers import is_torch_available, PreTrainedTokenizerFast",
"if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] =",
"all_predictions[example[\"id\"]] = best_non_null_pred # Make `predictions` JSON-serializable by casting np.float back to float.",
"for i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features):",
"# The dictionaries we have to fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict()",
"\"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab = Mecab() def tokenize(text): # return text.split(\" \")",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"we compare to the null prediction using the threshold. score_diff = ( null_score",
"`optional`, defaults to :obj:`True`): Whether this process is the main process or not",
"logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the\"",
"Optional[str] = None, is_world_process_zero: bool = True, consider=20 ): \"\"\" Post-processes the predictions",
"logits. start_indexes = np.argsort(start_logits)[ -1 : -consider - 1 : -1 ].tolist() end_indexes",
"of all scores (we do it with numpy to stay independent from torch/tf",
"utilities for question answering. \"\"\" import collections import json import logging import os",
"int = 20, max_answer_length: int = 30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str]",
"with `prefix` added to their names. is_world_process_zero (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether",
"= features[feature_index].get( \"token_is_max_context\", None ) # Update minimum null prediction. feature_null_score = start_logits[0]",
"to predict a null answer). Only useful when :obj:`version_2_with_negative` is :obj:`True`. output_dir (:obj:`str`,",
"get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\",",
"0): The threshold used to select the null answer: if the best answer",
"HuggingFace Team All rights reserved. # # Licensed under the Apache License, Version",
"f\"Post-processing {len(examples)} example predictions split into {len(features)} features.\" ) # Let's loop over",
"model to convert them to answers that are substrings of the original contexts.",
"f\"{output_dir} is not a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix is",
"features, predictions: Tuple[np.ndarray, np.ndarray], version_2_with_negative: bool = False, n_best_size: int = 20, max_answer_length:",
"are the indices of the features associated to the current example. feature_indices =",
"have not a single non-null prediction, we create a fake prediction to avoid",
"than the maximum length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length =",
"train from scratch.\" ) # Tokenizer check: this script requires a fast tokenizer.",
"# you may not use this file except in compliance with the License.",
"answers. n_best_size (:obj:`int`, `optional`, defaults to 20): The total number of n-best predictions",
"must match the number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to",
"`n_best_size` predictions. predictions = sorted( prelim_predictions, key=lambda x: x[\"score\"], reverse=True )[:n_best_size] # Add",
"end_logits[end_index], } ) if version_2_with_negative: # Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score",
"> feature_null_score ): min_null_prediction = { \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0],",
"multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray,",
"tokenize(text): # return text.split(\" \") return mecab.morphs(text) def sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed:",
"if \"validation\" not in datasets: raise ValueError(\"--do_eval requires a validation dataset\") return last_checkpoint,",
"example to its corresponding features. example_id_to_index = {k: i for i, k in",
"(:obj:`int`, `optional`, defaults to 30): The maximum length of an answer that can",
"min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets: raise ValueError(\"--do_eval requires a validation dataset\")",
"# Then we compare to the null prediction using the threshold. score_diff =",
"the indices of the features associated to the current example. feature_indices = features_per_example[example_index]",
"than the score of the null answer minus this threshold, the null answer",
"number of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or",
"and predictions[0][\"text\"] == \"\" ): predictions.insert( 0, {\"text\": \"empty\", \"start_logit\": 0.0, \"end_logit\": 0.0,",
"1 : -1].tolist() for start_index in start_indexes: for end_index in end_indexes: # Don't",
"Checkout the big table of models \" \"at https://huggingface.co/transformers/index.html#bigtable to find the model",
"example_id_to_index = {k: i for i, k in enumerate(examples[\"id\"])} features_per_example = collections.defaultdict(list) for",
"min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = { \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\":",
"import Mecab import torch import random from transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils",
"#\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if",
"possibilities for the `n_best_size` greater start and end logits. start_indexes = np.argsort(start_logits)[ -1",
"softmax of all scores (we do it with numpy to stay independent from",
"for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\"",
"version_2_with_negative: # Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only",
"prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json, ) nbest_file",
"enumerate(tqdm(examples)): # Those are the indices of the features associated to the current",
"Don't consider out-of-scope answers, either because the indices are out of bounds or",
"the end logits respectively. Its first dimension must match the number of elements",
"be aligned on the fact they `want` to predict a null answer). Only",
"License for the specific language governing permissions and # limitations under the License.",
"offset_mapping[end_index] is None ): continue # Don't consider answers with a length that",
"defaults to 0): The threshold used to select the null answer: if the",
"in predictions ): predictions.append(min_null_prediction) # Use the offsets to gather the answer text",
"works for models that have a fast tokenizer. Checkout the big table of",
"in ban_words: if ban_word in candidate_word: flag=True break if flag: print(\"BAN\",candidate_word) continue else:",
"we first need to find the best non-empty prediction. i = 0 while",
"our predictions. for prob, pred in zip(probs, predictions): pred[\"probability\"] = prob # Pick",
"= predictions[0][\"text\"] else: # Otherwise we first need to find the best non-empty",
"\"License\"); # you may not use this file except in compliance with the",
"`optional`, defaults to 0): The threshold used to select the null answer: if",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"not any( p[\"offsets\"] == (0, 0) for p in predictions ): predictions.append(min_null_prediction) #",
"1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist()",
"examples: The non-preprocessed dataset (see the main script for more information). features: The",
"length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\" ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if",
"answer that can be generated. This is needed because the start and end",
"feature_null_score = start_logits[0] + end_logits[0] if ( min_null_prediction is None or min_null_prediction[\"score\"] >",
"null_score_diff_threshold: float = 0.0, output_dir: Optional[str] = None, prefix: Optional[str] = None, is_world_process_zero:",
"assert ( len(predictions) == 2 ), \"`predictions` should be a tuple with two",
"\"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go through all possibilities for",
"f\"null_odds_{prefix}\".json, ) logger.info(f\"Saving predictions to {prediction_file}.\") with open(prediction_file, \"w\") as writer: writer.write(json.dumps(all_predictions, indent=4,",
"the model for this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This",
"check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last checkpoint. last_checkpoint = None if (",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"end_indexes: # Don't consider out-of-scope answers, either because the indices are out of",
"null_score = min_null_prediction[\"score\"] # Only keep the best `n_best_size` predictions. predictions = sorted(",
"in writing, software # distributed under the License is distributed on an \"AS",
"with two elements (start_logits, end_logits).\" all_start_logits, all_end_logits = predictions assert len(predictions[0]) == len(",
"limitations under the License. \"\"\" Pre-processing Post-processing utilities for question answering. \"\"\" import",
"max_answer_length ): continue # Don't consider answer that don't have the maximum context",
"edge case we have not a single non-null prediction, we create a fake",
"import logging import os from typing import Optional, Tuple import numpy as np",
"Looping through all the features associated to the current example. for feature_index in",
"ensure_ascii=False) + \"\\n\") return all_predictions def check_no_error(training_args, data_args, tokenizer, datasets): # Detecting last",
"\"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\"",
"Optional, Tuple import numpy as np from tqdm.auto import tqdm from konlpy.tag import",
"import tqdm from konlpy.tag import Mecab import torch import random from transformers import",
"answers with a length that is either < 0 or > max_answer_length. if",
"by casting np.float back to float. all_nbest_json[example[\"id\"]] = [ { k: ( float(v)",
"on one another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The threshold used to",
"exp_scores / exp_scores.sum() # Include the probabilities in our predictions. for prob, pred",
"scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)}",
"null prediction using the threshold. score_diff = ( null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"]",
"is not possible, this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"] else:",
"sigmoid(x): return 1/(1+np.exp(-x)) def set_seed(seed: int): \"\"\" Helper function for reproducible behavior to",
"this \" \"requirement\" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length})",
"output_dir, \"nbest_predictions.json\" if prefix is None else f\"nbest_predictions_{prefix}\".json, ) if version_2_with_negative: null_odds_file =",
"if flag: print(\"BAN\",candidate_word) continue else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ),",
"and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None",
"): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise",
"# Make `predictions` JSON-serializable by casting np.float back to float. all_nbest_json[example[\"id\"]] = [",
"ValueError( \"This example script only works for models that have a fast tokenizer.",
"ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\",",
"answers, either because the indices are out of bounds or correspond # to",
"the null answer for an example giving several features is the minimum of",
"example[\"context\"] for pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0] : offsets[1]]",
"of elements of :obj:`features`. version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not",
"the start and end predictions are not conditioned on one another. null_score_diff_threshold (:obj:`float`,",
"between best and null answers, are saved in `output_dir`. prefix (:obj:`str`, `optional`): If",
"float( score_diff ) # To be JSON-serializable. if score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] =",
"score_diff > null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred",
"features.\" ) # Let's loop over all the examples! for example_index, example in",
"in the original context. context = example[\"context\"] for pred in predictions: offsets =",
"overcome.\" ) elif last_checkpoint is not None: logger.info( f\"Checkpoint detected, resuming training at",
"Don't consider answers with a length that is either < 0 or >",
"answer is not possible, this is easy. if not version_2_with_negative: all_predictions[example[\"id\"]] = predictions[0][\"text\"]",
"typing import Optional, Tuple import numpy as np from tqdm.auto import tqdm from",
"prefix is None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join( output_dir, \"nbest_predictions.json\" if prefix",
"= predictions assert len(predictions[0]) == len( features ), f\"Got {len(predictions[0])} predictions and {len(features)}",
"from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\",",
"None, prefix: Optional[str] = None, is_world_process_zero: bool = True, consider=20 ): \"\"\" Post-processes",
"looking for an answer. max_answer_length (:obj:`int`, `optional`, defaults to 30): The maximum length",
"with no answers. n_best_size (:obj:`int`, `optional`, defaults to 20): The total number of",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"directory ({training_args.output_dir}) already exists and is not empty. \" \"Use --overwrite_output_dir to overcome.\"",
"\"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\", \"왜냐하면\", \"아무래도\") mecab",
"it was removed because of its low score. if version_2_with_negative and not any(",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"of the original contexts. This is the base postprocessing functions for models that",
"# # Unless required by applicable law or agreed to in writing, software",
"torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions(",
"express or implied. # See the License for the specific language governing permissions",
"threshold, the null answer is selected for this example (note that the score",
"features.\" # Build a map example to its corresponding features. example_id_to_index = {k:",
"transformers import is_torch_available, PreTrainedTokenizerFast from transformers.trainer_utils import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\",",
"None: logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change",
"to avoid # failure. if len(predictions) == 0 or ( len(predictions) == 1",
"30): The maximum length of an answer that can be generated. This is",
"a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script only",
"either express or implied. # See the License for the specific language governing",
"probabilities in our predictions. for prob, pred in zip(probs, predictions): pred[\"probability\"] = prob",
"their scores and logits) and, if :obj:`version_2_with_negative=True`, the dictionary of the scores differences",
"we have not a single non-null prediction, we create a fake prediction to",
"prediction if it was removed because of its low score. if version_2_with_negative and",
"The dictionaries we have to fill. all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() if",
"# Add the minimum null prediction prelim_predictions.append(min_null_prediction) null_score = min_null_prediction[\"score\"] # Only keep",
"requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( \"This example script",
"\"\"\" assert ( len(predictions) == 2 ), \"`predictions` should be a tuple with",
"# Go through all possibilities for the `n_best_size` greater start and end logits.",
"os.path.join( output_dir, \"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json, ) nbest_file = os.path.join(",
"this behavior, change \" \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\"",
"use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features, predictions:",
"import get_last_checkpoint logger = logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\",",
"the current example. for feature_index in feature_indices: # We grab the predictions of",
"token_is_max_context.get(str(start_index), False) ): continue flag=False candidate_word=example[\"context\"][offset_mapping[start_index][0]:offset_mapping[end_index][1]] for ban_word in ban_words: if ban_word in",
"( min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction = { \"offsets\":",
"> tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length",
"tokenizer.model_max_length: logger.warn( f\"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for",
"the License. # You may obtain a copy of the License at #",
"predictions[i] # Then we compare to the null prediction using the threshold. score_diff",
"back the minimum null prediction if it was removed because of its low",
"context = example[\"context\"] for pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] = context[offsets[0]",
"end logits. Args: examples: The non-preprocessed dataset (see the main script for more",
"or offset_mapping[end_index] is None ): continue # Don't consider answers with a length",
"over all the examples! for example_index, example in enumerate(tqdm(examples)): # Those are the",
"\"\"\" import collections import json import logging import os from typing import Optional,",
"`optional`, defaults to 20): The total number of n-best predictions to generate when",
"context # available in the current feature. token_is_max_context = features[feature_index].get( \"token_is_max_context\", None )",
"of bounds or correspond # to part of the input_ids that are not",
"].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider - 1 : -1].tolist() for start_index in",
"- best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff ) # To be",
"- 1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 : -consider - 1 :",
"ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\") as writer: writer.write(json.dumps(all_nbest_json,",
"the null answer is selected for this example (note that the score of",
"to part of the input_ids that are not in the context. if (",
"is not None: logger.info( f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this",
"30, null_score_diff_threshold: float = 0.0, output_dir: Optional[str] = None, prefix: Optional[str] = None,",
"example script only works for models that have a fast tokenizer. Checkout the",
"base postprocessing functions for models that only return start and end logits. Args:",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"+ end_logits[0] if ( min_null_prediction is None or min_null_prediction[\"score\"] > feature_null_score ): min_null_prediction",
"if ( end_index < start_index or end_index - start_index + 1 > max_answer_length",
"torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def postprocess_qa_predictions( examples, features, predictions: Tuple[np.ndarray, np.ndarray],",
"start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative:",
"({training_args.output_dir}) already exists and is not empty. \" \"Use --overwrite_output_dir to overcome.\" )",
"else: print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]),",
"the examples! for example_index, example in enumerate(tqdm(examples)): # Those are the indices of",
"of the model for this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] #",
"Let's loop over all the examples! for example_index, example in enumerate(tqdm(examples)): # Those",
"original # context. offset_mapping = features[feature_index][\"offset_mapping\"] # Optional `token_is_max_context`, if provided we will",
"answer text in the original context. context = example[\"context\"] for pred in predictions:",
"# Copyright 2020 The HuggingFace Team All rights reserved. # # Licensed under",
"null_score - best_non_null_pred[\"start_logit\"] - best_non_null_pred[\"end_logit\"] ) scores_diff_json[example[\"id\"]] = float( score_diff ) # To",
"its corresponding features. example_id_to_index = {k: i for i, k in enumerate(examples[\"id\"])} features_per_example",
"Optional `token_is_max_context`, if provided we will remove answers that do not have the",
"pred in predictions ] # If we have an output_dir, let's save all",
"features: The processed dataset (see the main script for more information). predictions (:obj:`Tuple[np.ndarray,",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"to 20): The total number of n-best predictions to generate when looking for",
"is :obj:`True`. output_dir (:obj:`str`, `optional`): If provided, the dictionaries of predictions, n_best predictions",
"\"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } ) if version_2_with_negative: #",
"logger.setLevel(logging.INFO if is_world_process_zero else logging.WARN) logger.info( f\"Post-processing {len(examples)} example predictions split into {len(features)}",
"torch/tf in this file, using # the LogSumExp trick). scores = np.array([pred.pop(\"score\") for",
"for start_index in start_indexes: for end_index in end_indexes: # Don't consider out-of-scope answers,",
"): predictions.append(min_null_prediction) # Use the offsets to gather the answer text in the",
"the null answer on each feature: all features must be aligned on the",
"end_index in end_indexes: # Don't consider out-of-scope answers, either because the indices are",
"print(\"ACCEPT\",candidate_word) prelim_predictions.append( { \"offsets\": ( offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\":",
"# Use the offsets to gather the answer text in the original context.",
"features is the minimum of the scores for the null answer on each",
"answer that don't have the maximum context available (if such information is #",
"), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index], } )",
"all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO if is_world_process_zero",
"score of the null answer for an example giving several features is the",
"offset_mapping[start_index][0], offset_mapping[end_index][1], ), #\"score\": start_logits[start_index]+end_logits[end_index], \"score\": sigmoid(start_logits[start_index])*sigmoid(end_logits[end_index]), #\"score\": max(start_logits[start_index]+5,0)*max(end_logits[end_index]+5,0), \"start_logit\": start_logits[start_index], \"end_logit\": end_logits[end_index],",
"back to float. all_nbest_json[example[\"id\"]] = [ { k: ( float(v) if isinstance(v, (np.float16,",
"this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what will",
"provided, the dictionaries of predictions, n_best predictions (with their scores and logits) and,",
"\"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0], } # Go through",
"correspond # to part of the input_ids that are not in the context.",
"f\"Output directory ({training_args.output_dir}) already exists and is not empty. \" \"Use --overwrite_output_dir to",
"predictions to generate when looking for an answer. max_answer_length (:obj:`int`, `optional`, defaults to",
"set_seed(seed: int): \"\"\" Helper function for reproducible behavior to set the seed in",
"({data_args.max_seq_length}) is larger than the maximum length for the\" f\"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.\"",
"for an example giving several features is the minimum of the scores for",
"tqdm from konlpy.tag import Mecab import torch import random from transformers import is_torch_available,",
"except in compliance with the License. # You may obtain a copy of",
"only return start and end logits. Args: examples: The non-preprocessed dataset (see the",
"# Don't consider out-of-scope answers, either because the indices are out of bounds",
"> null_score_diff_threshold: all_predictions[example[\"id\"]] = \"\" else: #all_predictions[example[\"id\"]] = best_non_null_pred[\"text\"] all_predictions[example[\"id\"]] = best_non_null_pred #",
"the maximum context available (if such information is # provided). if ( token_is_max_context",
"be generated. This is needed because the start and end predictions are not",
"collections import json import logging import os from typing import Optional, Tuple import",
"None prelim_predictions = [] # Looping through all the features associated to the",
"the offsets to gather the answer text in the original context. context =",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is None",
"contains examples with no answers. n_best_size (:obj:`int`, `optional`, defaults to 20): The total",
"= collections.OrderedDict() all_nbest_json = collections.OrderedDict() if version_2_with_negative: scores_diff_json = collections.OrderedDict() # Logging. logger.setLevel(logging.INFO",
"should be done). \"\"\" assert ( len(predictions) == 2 ), \"`predictions` should be",
"): min_null_prediction = { \"offsets\": (0, 0), \"score\": feature_null_score, \"start_logit\": start_logits[0], \"end_logit\": end_logits[0],",
"best_non_null_pred = predictions[i] # Then we compare to the null prediction using the",
"= prob # Pick the best prediction. If the null answer is not",
"prob, pred in zip(probs, predictions): pred[\"probability\"] = prob # Pick the best prediction.",
"k: ( float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v ) for k,",
"= os.path.join( output_dir, \"predictions.json\" if prefix is None else f\"predictions_{prefix}\".json, ) nbest_file =",
"= min_null_prediction[\"score\"] # Only keep the best `n_best_size` predictions. predictions = sorted( prelim_predictions,",
"another. null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0): The threshold used to select the",
"= np.argsort(start_logits)[ -1 : -consider - 1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1",
"# failure. if len(predictions) == 0 or ( len(predictions) == 1 and predictions[0][\"text\"]",
"max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) if \"validation\" not in datasets: raise ValueError(\"--do_eval requires a",
"`predictions` JSON-serializable by casting np.float back to float. all_nbest_json[example[\"id\"]] = [ { k:",
"(if such information is # provided). if ( token_is_max_context is not None and",
"some the positions in our logits to span of texts in the original",
"information). features: The processed dataset (see the main script for more information). predictions",
"the original context. context = example[\"context\"] for pred in predictions: offsets = pred.pop(\"offsets\")",
"import Optional, Tuple import numpy as np from tqdm.auto import tqdm from konlpy.tag",
"greater start and end logits. start_indexes = np.argsort(start_logits)[ -1 : -consider - 1",
"n-best predictions to generate when looking for an answer. max_answer_length (:obj:`int`, `optional`, defaults",
"an example giving several features is the minimum of the scores for the",
"get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f\"Output directory",
"writer: writer.write(json.dumps(all_predictions, indent=4, ensure_ascii=False) + \"\\n\") logger.info(f\"Saving nbest_preds to {nbest_file}.\") with open(nbest_file, \"w\")",
"{ k: ( float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v ) for",
"logging/saves should be done). \"\"\" assert ( len(predictions) == 2 ), \"`predictions` should",
"context. context = example[\"context\"] for pred in predictions: offsets = pred.pop(\"offsets\") pred[\"text\"] =",
"we create a fake prediction to avoid # failure. if len(predictions) == 0",
"\"at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this \" \"requirement\" )",
"os.path.isdir(output_dir), f\"{output_dir} is not a directory.\" prediction_file = os.path.join( output_dir, \"predictions.json\" if prefix",
"not the underlying dataset contains examples with no answers. n_best_size (:obj:`int`, `optional`, defaults",
"of the scores differences between best and null answers, are saved in `output_dir`.",
"ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not empty. \" \"Use --overwrite_output_dir",
"np.argsort(start_logits)[ -1 : -consider - 1 : -1 ].tolist() end_indexes = np.argsort(end_logits)[-1 :",
"None, is_world_process_zero: bool = True, consider=20 ): \"\"\" Post-processes the predictions of a",
"logging.getLogger(__name__) ban_words=(\"이따금\",\"아마\",\"절대로\",\"무조건\",\"한때\",\"대략\",\"오직\", \"오로지\",\"감히\",\"최소\",\"아예\",\"반드시\",\"꼭\",\"때때로\",\"이미\", \"심지어\" ,\"종종\",\"졸곧\",\"약간\",\"기꺼이\", \"비록\",\"꾸준히\",\"일부러\",\"어쩔\", \"문득\", \"어쨌든\", \"순전히\", \"필수\",\"자칫\", \"다소\", \"간혹\", \"적어도\","
] |
[
"the trained flow to the training data and test data trainout = flow(x[0])",
"delay=20): # set_size is the number of waves # data_length is the number",
"input data = [None, zip(x, y)] # print data ### Create reservoir #",
"pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g')",
"= [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) #",
"data_length, delay) print numpy.shape(x_test) # should be (set_size, data_dim, point_dim) (in this case",
"# train the flow flow.train(data) #apply the trained flow to the training data",
"= mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply the trained",
"nb in range(set_size): # waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in",
"empty input_set = [] target_set = [] # generate set_size signals for nb",
"numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP format input data = [None, zip(x,",
"5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show() # end",
"= gen_random_data(set_size, data_length, delay) # print x,y print numpy.shape(x) # should be (set_size,",
"data generating function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the number of",
"ny, 5) # pylab.plot(testout2, 'g') pylab.show() # end of main return None #",
"a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1)",
"function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the number of waves #",
"flow(x[0]) # gen test data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay) print",
"print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP format input data = [None,",
"flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results",
"sets starts empty input_set = [] target_set = [] # generate set_size signals",
"= [None, zip(x, y)] # print data ### Create reservoir # construct individual",
"testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) #",
"testing output and target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny,",
"= [] target_set = [] # generate set_size signals for nb in range(set_size):",
"[numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave = [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay])",
"to the training data and test data trainout = flow(x[0]) # gen test",
"flow to the training data and test data trainout = flow(x[0]) # gen",
"\"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx = 2 ny =",
"results nx = 2 ny = 1 # plot a few inputs pylab.subplot(nx,",
"# pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show() # end of",
"delay) print numpy.shape(x_test) # should be (set_size, data_dim, point_dim) (in this case point_dim=1)",
"readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply the trained flow to",
"inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b')",
"mdp import Oger import numpy import pylab import random import math ### README",
"5) # pylab.plot(testout2, 'g') pylab.show() # end of main return None # data",
"number of points per wave # the target is delayed by delay #",
"nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build",
"x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) # Call to main",
"data ### Create reservoir # construct individual nodes, reservoir_size = 500 reservoir =",
"print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \"",
"set_size is the number of waves # data_length is the number of points",
"few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1) #",
"# pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g')",
"# should be (set_size, data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10]",
"# gen test data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test)",
"by delay # sets starts empty input_set = [] target_set = [] #",
"### Create reservoir # construct individual nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size,",
"generating function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the number of waves",
"waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave = [numpy.array([0])",
"end of main return None # data generating function def gen_random_data(set_size=100, data_length=500, delay=20):",
"= gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should be (set_size, data_dim, point_dim) (in",
"random import math ### README # the goal is to teach the reservoir",
"= Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network with MDP framework flow",
"readout = Oger.nodes.RidgeRegressionNode() # build network with MDP framework flow = mdp.Flow([reservoir, readout],",
"data = [None, zip(x, y)] # print data ### Create reservoir # construct",
"pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the input and target #",
"build network with MDP framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train",
"pylab.show() # end of main return None # data generating function def gen_random_data(set_size=100,",
"import math ### README # the goal is to teach the reservoir to",
"1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny,",
"y)] # print data ### Create reservoir # construct individual nodes, reservoir_size =",
"range(data_length)] target_wave = [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set,",
"should be (set_size, data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print",
"trainout = flow(x[0]) # gen test data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length,",
"case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1])",
"2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot the training",
"pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') # #plot the testing output",
"# generate set_size signals for nb in range(set_size): # waves start empty input_wave",
"# set_size is the number of waves # data_length is the number of",
"with a certain delay def main(): ### Create/Load dataset set_size=200 data_length=100 delay=25 [x,",
"= flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot",
"and target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) #",
"pylab.plot(x[2],'g') #plot the input and target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') #",
"500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network with MDP",
"the reservoir to recreate the input signal with a certain delay def main():",
"(set_size, data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) #",
"'b') #plot the training output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx,",
"\" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx = 2 ny = 1",
"numpy.shape(x) # should be (set_size, data_dim, point_dim) (in this case point_dim=1) # print",
"of main return None # data generating function def gen_random_data(set_size=100, data_length=500, delay=20): #",
"data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print",
"flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply the",
"# data generating function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the number",
"ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') # #plot",
"# pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot the training output",
"2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing output and target # pylab.subplot(nx,",
"print numpy.shape(x_test) # should be (set_size, data_dim, point_dim) (in this case point_dim=1) #",
"math ### README # the goal is to teach the reservoir to recreate",
"MDP framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data)",
"testout2 = flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx",
"of points per wave # the target is delayed by delay # sets",
"pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the",
"set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length, delay) # print x,y print",
"1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the input and",
"start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave = [numpy.array([0]) for",
"# print numpy.shape(y) # create MDP format input data = [None, zip(x, y)]",
"print numpy.shape(x) # should be (set_size, data_dim, point_dim) (in this case point_dim=1) #",
"[x, y] = gen_random_data(set_size, data_length, delay) # print x,y print numpy.shape(x) # should",
"goal is to teach the reservoir to recreate the input signal with a",
"testout1)) # plot results nx = 2 ny = 1 # plot a",
"ny = 1 # plot a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input')",
"delay) # print x,y print numpy.shape(x) # should be (set_size, data_dim, point_dim) (in",
"4) # pylab.plot(testout1, 'g') # #plot the testing output and target # pylab.subplot(nx,",
"construct individual nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode()",
"# create MDP format input data = [None, zip(x, y)] # print data",
"x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \" +",
"# pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the input and target",
"flow flow.train(data) #apply the trained flow to the training data and test data",
"[] # generate set_size signals for nb in range(set_size): # waves start empty",
"[numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) # Call",
"# print x,y print numpy.shape(x) # should be (set_size, data_dim, point_dim) (in this",
"set_size signals for nb in range(set_size): # waves start empty input_wave = [numpy.array([20.0*random.random()-10.0])",
"pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show() # end of main return None",
"gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should be (set_size, data_dim, point_dim) (in this",
"return None # data generating function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is",
"README # the goal is to teach the reservoir to recreate the input",
"point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y)",
"in range(set_size): # waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)]",
"numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1))",
"print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0],",
"# #plot the testing output and target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b')",
"pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing output and target # pylab.subplot(nx, ny,",
"dataset set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length, delay) # print x,y",
"y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should be (set_size, data_dim, point_dim)",
"delayed by delay # sets starts empty input_set = [] target_set = []",
"str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx = 2 ny = 1 # plot",
"and target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) #",
"testing output and target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny,",
"output and target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5)",
"= 2 ny = 1 # plot a few inputs pylab.subplot(nx, ny, 1)",
"ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the input",
"the testing output and target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx,",
"input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network with MDP framework flow = mdp.Flow([reservoir,",
"the goal is to teach the reservoir to recreate the input signal with",
"data trainout = flow(x[0]) # gen test data set_size=2 [x_test, y_test] = gen_random_data(set_size,",
"pylab.plot(y[0], 'b') #plot the training output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target')",
"numpy import pylab import random import math ### README # the goal is",
"pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot the training output and target pylab.subplot(nx,",
"x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP format input data =",
"training output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout,",
"[x_test, y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should be (set_size, data_dim,",
"the flow flow.train(data) #apply the trained flow to the training data and test",
"# pylab.plot(x[2],'g') #plot the input and target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r')",
"# pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') # #plot the testing",
"target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) # Call to main if __name__=='__main__': main()",
"# waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave =",
"2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing",
"and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output')",
"plot a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny,",
"Create/Load dataset set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length, delay) # print",
"zip(x, y)] # print data ### Create reservoir # construct individual nodes, reservoir_size",
"pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot the training output and",
"the input and target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny,",
"#plot the input and target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx,",
"the input signal with a certain delay def main(): ### Create/Load dataset set_size=200",
"MDP format input data = [None, zip(x, y)] # print data ### Create",
"the testing output and target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx,",
"input and target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2)",
"gen_random_data(set_size, data_length, delay) # print x,y print numpy.shape(x) # should be (set_size, data_dim,",
"and test data trainout = flow(x[0]) # gen test data set_size=2 [x_test, y_test]",
"waves # data_length is the number of points per wave # the target",
"main(): ### Create/Load dataset set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length, delay)",
"in range(data_length)] target_wave = [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return",
"#plot the testing output and target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') #",
"ny, 2) # pylab.plot(y[0], 'b') #plot the training output and target pylab.subplot(nx, ny,",
"data_length=500, delay=20): # set_size is the number of waves # data_length is the",
"# print data ### Create reservoir # construct individual nodes, reservoir_size = 500",
"x,y print numpy.shape(x) # should be (set_size, data_dim, point_dim) (in this case point_dim=1)",
"nx = 2 ny = 1 # plot a few inputs pylab.subplot(nx, ny,",
"reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network with MDP framework",
"[] target_set = [] # generate set_size signals for nb in range(set_size): #",
"4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') # #plot the",
"ny, 1) # pylab.plot(x[2],'g') #plot the input and target # pylab.subplot(nx, ny, 2)",
"1 # plot a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() #",
"#plot the training output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny,",
"print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP format input data",
"main return None # data generating function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size",
"ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the",
"= flow(x[0]) # gen test data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay)",
"target_wave = [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set])",
"import Oger import numpy import pylab import random import math ### README #",
"and target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) #",
"(in this case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) #",
"train the flow flow.train(data) #apply the trained flow to the training data and",
"= [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave = [numpy.array([0]) for x in range(delay)]",
"recreate the input signal with a certain delay def main(): ### Create/Load dataset",
"pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show()",
"= [] # generate set_size signals for nb in range(set_size): # waves start",
"# pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show() # end of main return",
"(set_size, data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1",
"delay=25 [x, y] = gen_random_data(set_size, data_length, delay) # print x,y print numpy.shape(x) #",
"= flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx =",
"wave # the target is delayed by delay # sets starts empty input_set",
"reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network",
"output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g',",
"ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing output and target #",
"data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length, delay) # print x,y print numpy.shape(x)",
"flow(x_test[1]) print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx = 2",
"pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show() # end of main",
"the training output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2)",
"is to teach the reservoir to recreate the input signal with a certain",
"# plot results nx = 2 ny = 1 # plot a few",
"for nb in range(set_size): # waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x",
"for x in range(data_length)] target_wave = [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave))",
"print data ### Create reservoir # construct individual nodes, reservoir_size = 500 reservoir",
"pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing output and target",
"#apply the trained flow to the training data and test data trainout =",
"delay def main(): ### Create/Load dataset set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size,",
"teach the reservoir to recreate the input signal with a certain delay def",
"to recreate the input signal with a certain delay def main(): ### Create/Load",
"pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1)",
"delay # sets starts empty input_set = [] target_set = [] # generate",
"target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1,",
"point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP format",
"target is delayed by delay # sets starts empty input_set = [] target_set",
"ny, 4) # pylab.plot(testout1, 'g') # #plot the testing output and target #",
"pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot",
"# print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP format input",
"numpy.shape(y) # create MDP format input data = [None, zip(x, y)] # print",
"label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing output and",
"Oger import numpy import pylab import random import math ### README # the",
"data_length is the number of points per wave # the target is delayed",
"#plot the testing output and target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') #",
"signals for nb in range(set_size): # waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for",
"this case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 =",
"is the number of points per wave # the target is delayed by",
"create MDP format input data = [None, zip(x, y)] # print data ###",
"a certain delay def main(): ### Create/Load dataset set_size=200 data_length=100 delay=25 [x, y]",
"= Oger.nodes.RidgeRegressionNode() # build network with MDP framework flow = mdp.Flow([reservoir, readout], verbose=1)",
"Oger.nodes.RidgeRegressionNode() # build network with MDP framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode)",
"# pylab.plot(y[0], 'b') #plot the training output and target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b',",
"# build network with MDP framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) #",
"import numpy import pylab import random import math ### README # the goal",
"target pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend()",
"test data trainout = flow(x[0]) # gen test data set_size=2 [x_test, y_test] =",
"the number of waves # data_length is the number of points per wave",
"label='input') pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) #",
"Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network with MDP framework flow =",
"print x,y print numpy.shape(x) # should be (set_size, data_dim, point_dim) (in this case",
"# plot a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx,",
"pylab.legend() #plot the testing output and target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b')",
"1) # pylab.plot(x[2],'g') #plot the input and target # pylab.subplot(nx, ny, 2) #",
"# pylab.plot(testout2, 'g') pylab.show() # end of main return None # data generating",
"pylab import random import math ### README # the goal is to teach",
"pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') # #plot the testing output and target",
"point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0])",
"pylab.plot(testout2, 'g') pylab.show() # end of main return None # data generating function",
"reservoir # construct individual nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout",
"= 1 # plot a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend()",
"with MDP framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow",
"verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply the trained flow to the",
"case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create MDP",
"y] = gen_random_data(set_size, data_length, delay) # print x,y print numpy.shape(x) # should be",
"format input data = [None, zip(x, y)] # print data ### Create reservoir",
"'g', label='output') pylab.legend() #plot the testing output and target # pylab.subplot(nx, ny, 4)",
"# sets starts empty input_set = [] target_set = [] # generate set_size",
"starts empty input_set = [] target_set = [] # generate set_size signals for",
"this case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4]) # print numpy.shape(y) # create",
"data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should be",
"reservoir to recreate the input signal with a certain delay def main(): ###",
"# end of main return None # data generating function def gen_random_data(set_size=100, data_length=500,",
"target # pylab.subplot(nx, ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2,",
"pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') #",
"Create reservoir # construct individual nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05)",
"# pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g')",
"def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the number of waves # data_length",
"training data and test data trainout = flow(x[0]) # gen test data set_size=2",
"input_set = [] target_set = [] # generate set_size signals for nb in",
"[None, zip(x, y)] # print data ### Create reservoir # construct individual nodes,",
"certain delay def main(): ### Create/Load dataset set_size=200 data_length=100 delay=25 [x, y] =",
"gen test data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) #",
"in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) # Call to main if",
"data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 =",
"Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply the trained flow to the training",
"points per wave # the target is delayed by delay # sets starts",
"test data set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should",
"per wave # the target is delayed by delay # sets starts empty",
"is delayed by delay # sets starts empty input_set = [] target_set =",
"### Create/Load dataset set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length, delay) #",
"input signal with a certain delay def main(): ### Create/Load dataset set_size=200 data_length=100",
"2) # pylab.plot(y[0], 'b') #plot the training output and target pylab.subplot(nx, ny, 2)",
"output and target # pylab.subplot(nx, ny, 4) # pylab.plot(y_test[0],'b') # pylab.subplot(nx, ny, 4)",
"point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print",
"def main(): ### Create/Load dataset set_size=200 data_length=100 delay=25 [x, y] = gen_random_data(set_size, data_length,",
"+ str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx = 2 ny = 1 #",
"2 ny = 1 # plot a few inputs pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r',",
"x in range(data_length)] target_wave = [numpy.array([0]) for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave))",
"be (set_size, data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x[0]),numpy.shape(x[1]),numpy.shape(x[2]),numpy.shape(x[3]),numpy.shape(x[4])",
"# the target is delayed by delay # sets starts empty input_set =",
"# pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot the training output and target",
"pylab.subplot(nx, ny, 2) pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot",
"range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) # Call to main if __name__=='__main__':",
"ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx,",
"set_size=2 [x_test, y_test] = gen_random_data(set_size, data_length, delay) print numpy.shape(x_test) # should be (set_size,",
"# pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') # pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot",
"### README # the goal is to teach the reservoir to recreate the",
"empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave = [numpy.array([0]) for x",
"pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the input and target # pylab.subplot(nx, ny,",
"target # pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0],",
"plot results nx = 2 ny = 1 # plot a few inputs",
"None # data generating function def gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the",
"import mdp import Oger import numpy import pylab import random import math ###",
"input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave = [numpy.array([0]) for x in",
"individual nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() #",
"import pylab import random import math ### README # the goal is to",
"# the goal is to teach the reservoir to recreate the input signal",
"'g') # #plot the testing output and target # pylab.subplot(nx, ny, 5) #",
"target_set = [] # generate set_size signals for nb in range(set_size): # waves",
"# construct individual nodes, reservoir_size = 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout =",
"generate set_size signals for nb in range(set_size): # waves start empty input_wave =",
"range(set_size): # waves start empty input_wave = [numpy.array([20.0*random.random()-10.0]) for x in range(data_length)] target_wave",
"flow.train(data) #apply the trained flow to the training data and test data trainout",
"data and test data trainout = flow(x[0]) # gen test data set_size=2 [x_test,",
"(in this case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2",
"'g') pylab.show() # end of main return None # data generating function def",
"mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply the trained flow",
"be (set_size, data_dim, point_dim) (in this case point_dim=1) # print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1])",
"pylab.plot(y[0],'b', label='target') pylab.subplot(nx, ny, 2) pylab.plot(trainout, 'g', label='output') pylab.legend() #plot the testing output",
"of waves # data_length is the number of points per wave # the",
"network with MDP framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the",
"ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b') #plot the",
"gen_random_data(set_size=100, data_length=500, delay=20): # set_size is the number of waves # data_length is",
"number of waves # data_length is the number of points per wave #",
"to teach the reservoir to recreate the input signal with a certain delay",
"signal with a certain delay def main(): ### Create/Load dataset set_size=200 data_length=100 delay=25",
"numpy.shape(x_test) # should be (set_size, data_dim, point_dim) (in this case point_dim=1) # print",
"label='output') pylab.legend() #plot the testing output and target # pylab.subplot(nx, ny, 4) #",
"for x in range(delay)] target_wave.extend(input_wave[:-delay]) input_set.append(numpy.array(input_wave)) target_set.append(numpy.array(target_wave)) return numpy.array([input_set, target_set]) # Call to",
"is the number of waves # data_length is the number of points per",
"trained flow to the training data and test data trainout = flow(x[0]) #",
"# pylab.subplot(nx, ny, 2) # pylab.plot(x[0],'r') # pylab.subplot(nx, ny, 2) # pylab.plot(y[0], 'b')",
"print \"NRMSE: \" + str(Oger.utils.nrmse(y_test[0], testout1)) # plot results nx = 2 ny",
"# print x[0][0:10] print numpy.shape(x_test[0]),numpy.shape(x_test[1]) testout1 = flow(x_test[0]) testout2 = flow(x_test[1]) print \"NRMSE:",
"pylab.plot(testout1, 'g') # #plot the testing output and target # pylab.subplot(nx, ny, 5)",
"# data_length is the number of points per wave # the target is",
"data_length, delay) # print x,y print numpy.shape(x) # should be (set_size, data_dim, point_dim)",
"ny, 5) # pylab.plot(y_test[1],'b') # pylab.subplot(nx, ny, 5) # pylab.plot(testout2, 'g') pylab.show() #",
"the number of points per wave # the target is delayed by delay",
"the training data and test data trainout = flow(x[0]) # gen test data",
"# pylab.subplot(nx, ny, 4) # pylab.plot(testout1, 'g') # #plot the testing output and",
"= 500 reservoir = Oger.nodes.ReservoirNode(output_dim=reservoir_size, input_scaling=0.05) readout = Oger.nodes.RidgeRegressionNode() # build network with",
"print numpy.shape(y) # create MDP format input data = [None, zip(x, y)] #",
"the target is delayed by delay # sets starts empty input_set = []",
"pylab.subplot(nx, ny, 1) pylab.plot(x[0],'r', label='input') pylab.legend() # pylab.subplot(nx, ny, 1) # pylab.plot(x[1],'b') #",
"import random import math ### README # the goal is to teach the",
"framework flow = mdp.Flow([reservoir, readout], verbose=1) Oger.utils.make_inspectable(Oger.nodes.ReservoirNode) # train the flow flow.train(data) #apply",
"# pylab.plot(testout1, 'g') # #plot the testing output and target # pylab.subplot(nx, ny,",
"# pylab.subplot(nx, ny, 1) # pylab.plot(x[2],'g') #plot the input and target # pylab.subplot(nx,"
] |
[
"'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth',",
"'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy', 'shape_predictor': 'shape_predictor_68_face_landmarks.dat', 'moco':",
"'train_source': 'datasets/f2c/train_source', 'train_target': 'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq':",
"'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy',",
"'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth',",
"'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy', 'shape_predictor': 'shape_predictor_68_face_landmarks.dat',",
"= { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet':",
"'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy', 'shape_predictor': 'shape_predictor_68_face_landmarks.dat', 'moco': 'pretrained_models/moco_v2_800ep_pretrain.pth.tar'",
"= { 'train_source': 'datasets/f2c/train_source', 'train_target': 'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths =",
"model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy',",
"dataset_paths = { 'train_source': 'datasets/f2c/train_source', 'train_target': 'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths",
"{ 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy',",
"} model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet':",
"'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face':",
"'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy', 'shape_predictor': 'shape_predictor_68_face_landmarks.dat', 'moco': 'pretrained_models/moco_v2_800ep_pretrain.pth.tar' }",
"'datasets/f2c/train_source', 'train_target': 'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt',",
"'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy', 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy', 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy', 'shape_predictor':",
"{ 'train_source': 'datasets/f2c/train_source', 'train_target': 'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = {",
"'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50': 'pretrained_models/model_ir_se50.pth', 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth', 'mtcnn_pnet':",
"'train_target': 'datasets/f2c/train_target', 'test_source': 'datasets/f2c/test_source', 'test_target': 'datasets/f2c/test_target', } model_paths = { 'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt', 'ir_se50':"
] |
[
"PIL import Image from pylab import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray =",
"Image from pylab import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img) figure()",
"* img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img) figure() hist(imgArray.flatten(), 300) show() #",
"import Image from pylab import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img)",
"pylab import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img) figure() hist(imgArray.flatten(), 300)",
"from PIL import Image from pylab import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray",
"img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img) figure() hist(imgArray.flatten(), 300) show() # img.show()",
"import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img) figure() hist(imgArray.flatten(), 300) show()",
"from pylab import * img = Image.open('images/profile.jpg').convert('L') print(array(img)[500]) imgArray = array(img) figure() hist(imgArray.flatten(),"
] |
[
"exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s in series:",
"return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar !=",
"len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr,",
"= Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self): #",
"else: for tec in technicals: if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else:",
"__len__(self): return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self,",
"tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\"",
"= Helper self._series = [[{}]] self._variables = [[{}]] self._all_variables = [[{}]] self._size =",
"return True, self.new_row def __len__(self): return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\"",
"else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if self.ith_comb <",
"self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var):",
"NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger as logger from",
"... if self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else:",
"= s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if",
"else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist. try:",
"in technicals: if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else: for s in",
"value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif",
"-= 1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and",
"# self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar)",
"attr (str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series):",
"self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def",
"import ( Bar ) class DataContext(object): \"\"\" A DataContext expose data should be",
"-1 # 第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar = Bar(None, None, None,",
"# @TODO ... if self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] =",
"## # @file data_context.py # @brief # @author wondereamer # @version 0.1 #",
"2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase",
"TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args:",
"if self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr:",
"[[{}]] self._curbar = -1 self._Helper = Helper self._series = [[{}]] self._variables = [[{}]]",
"# 第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar = Bar(None, None, None, None,",
"滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1 return",
"name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\"",
"np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar =",
"self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar = -1 self._Helper =",
"def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def update_system_vars(self): # self.data",
"self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1 return False, None",
"\"\"\"\"\"\" def __init__(self, data): self.data = data def __setattr__(self, name, value): if name",
"= NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low =",
"var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data):",
"self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy = -1 #",
"self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name,",
"= self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1 return False, None self.next_datetime =",
"return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name,",
"= self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' %",
"s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals): if",
"Update technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for",
"else: for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar",
"rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar -=",
"self.high[0], self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self): # Update series defined by",
"# @brief # @author wondereamer # @version 0.1 # @date 2016-11-27 import datetime",
"'high') self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime')",
"% self.pcontract) raise return True, self.new_row def __len__(self): return len(self._Helper) def get_item(self, name):",
"self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec in technicals: if tec.is_multiple: for s",
"series defined by user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass",
"\"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb < len(self._all_variables): if self.ith_strategy <",
"# -*- coding: utf-8 -*- ## # @file data_context.py # @brief # @author",
"import TechnicalBase from quantity.digger.util import elogger as logger from quantity.digger.datastruct import ( Bar",
"Helper self._series = [[{}]] self._variables = [[{}]] self._all_variables = [[{}]] self._size = len(data.close)",
"@brief # @author wondereamer # @version 0.1 # @date 2016-11-27 import datetime from",
"self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data = data def __setattr__(self,",
"= [[{}]] self._all_variables = [[{}]] self._size = len(data.close) @property def raw_data(self): return self._Helper.data",
"A DataContext expose data should be visited by multiple strategie. which including bars",
"self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self):",
"添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]):",
"IndexError: pass else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if",
"SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self,",
"len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr:",
"@property def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def update_system_vars(self): #",
"= data def __setattr__(self, name, value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value)",
"utf-8 -*- ## # @file data_context.py # @brief # @author wondereamer # @version",
"-1 # 第j个策略 self.bar = Bar(None, None, None, None, None, None) self.new_row =",
"\"\"\" # @TODO ... if self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name]",
"NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values,",
"= np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar",
"data_context.py # @brief # @author wondereamer # @version 0.1 # @date 2016-11-27 import",
"data): self.data = data def __setattr__(self, name, value): if name == 'data': super(DataContextAttributeHelper,",
"@file data_context.py # @brief # @author wondereamer # @version 0.1 # @date 2016-11-27",
"self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余'",
"def __init__(self, Helper): data = Helper.data self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values,",
"self.bar = Bar(None, None, None, None, None, None) self.new_row = False self.next_datetime =",
"series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element()",
"len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value):",
"第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar = Bar(None, None, None, None, None,",
"attr, var): if self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var",
"s in tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\"",
"return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def",
"by user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for",
"update_user_vars(self): # Update series defined by user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values()",
"self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1 return False, None self.next_datetime",
"specific PContract, technicals and series of strategie. \"\"\" def __init__(self, Helper): data =",
"if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}])",
"by multiple strategie. which including bars of specific PContract, technicals and series of",
"NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index,",
"True, self.new_row def __len__(self): return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return",
"self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row",
"if self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr:",
"from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import",
"s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward()",
"s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series): if self.ith_strategy <",
"def add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr]",
"from quantity.digger.datastruct import ( Bar ) class DataContext(object): \"\"\" A DataContext expose data",
"value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name,",
"False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar != 0:",
"def curbar(self): return self._curbar + 1 @property def pcontract(self): return self._Helper.pcontract @property def",
"Update series defined by user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError:",
"def __setattr__(self, name, value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data",
"self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def update_system_vars(self):",
"wondereamer # @version 0.1 # @date 2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase,",
"# @version 0.1 # @date 2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries,",
"s}]) def add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]):",
"self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar)",
"import elogger as logger from quantity.digger.datastruct import ( Bar ) class DataContext(object): \"\"\"",
"logger from quantity.digger.datastruct import ( Bar ) class DataContext(object): \"\"\" A DataContext expose",
"= self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() #",
"raise return True, self.new_row def __len__(self): return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量",
"__init__(self, data): self.data = data def __setattr__(self, name, value): if name == 'data':",
"__setattr__(self, name, value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data =",
"序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr]",
"self.pcontract) raise return True, self.new_row def __len__(self): return len(self._Helper) def get_item(self, name): \"\"\"",
"datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util",
"__init__(self, Helper): data = Helper.data self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close')",
"DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar",
"= value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value)",
"\"\"\" def __init__(self, Helper): data = Helper.data self.open = NumberSeries(data.open.values, 'open') self.close =",
"self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def update_system_vars(self): # self.data = np.append(data, tracker.container_day)",
"self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row def __len__(self):",
"< len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value,",
"self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self): # Update series defined",
"self._curbar + 1 @property def pcontract(self): return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract",
"else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if self.ith_comb < len(self._variables): if self.ith_strategy",
"update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar)",
">= self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True,",
"None) self.new_row = False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar",
"self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var})",
"\"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ...",
"DataContext(object): \"\"\" A DataContext expose data should be visited by multiple strategie. which",
"if self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr:",
"coding: utf-8 -*- ## # @file data_context.py # @brief # @author wondereamer #",
"indic}]) def add_variable(self, attr, var): if self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]):",
"self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low",
"logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row def __len__(self): return len(self._Helper) def",
"in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values()",
"self.data = data def __setattr__(self, name, value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name,",
"isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def",
"= -1 # 第j个策略 self.bar = Bar(None, None, None, None, None, None) self.new_row",
"None, None, None, None, None) self.new_row = False self.next_datetime = datetime.datetime(2100, 1, 1)",
"var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data = data def __setattr__(self, name,",
"= Bar(None, None, None, None, None, None) self.new_row = False self.next_datetime = datetime.datetime(2100,",
"quantity.digger.datastruct import ( Bar ) class DataContext(object): \"\"\" A DataContext expose data should",
"else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data = data def",
"self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row =",
"def add_variable(self, attr, var): if self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr]",
"数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row def __len__(self): return len(self._Helper) def get_item(self,",
"should be visited by multiple strategie. which including bars of specific PContract, technicals",
"self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic})",
"if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data if name",
") class DataContext(object): \"\"\" A DataContext expose data should be visited by multiple",
"visited by multiple strategie. which including bars of specific PContract, technicals and series",
"IndexError: pass else: for tec in technicals: if tec.is_multiple: for s in tec.series.values():",
"isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量",
"self._Helper.data @property def curbar(self): return self._curbar + 1 @property def pcontract(self): return self._Helper.pcontract",
"属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series): if self.ith_strategy",
"== 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]:",
"try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec in technicals: if",
"self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if",
"value) else: self.add_variable(name, value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str):",
"self.new_row = False def update_user_vars(self): # Update series defined by user if exist.",
"添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb",
"NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy =",
"@property def pcontract(self): return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name):",
"self._curbar = -1 self._Helper = Helper self._series = [[{}]] self._variables = [[{}]] self._all_variables",
"s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size)",
"len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr:",
"PContract, technicals and series of strategie. \"\"\" def __init__(self, Helper): data = Helper.data",
"not self.new_row: self.last_curbar -= 1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0]",
"self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value})",
"第j个策略 self.bar = Bar(None, None, None, None, None, None) self.new_row = False self.next_datetime",
"None, None) self.new_row = False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals = [[{}]]",
"= var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self,",
"\"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1 return False,",
"import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from",
"series of strategie. \"\"\" def __init__(self, Helper): data = Helper.data self.open = NumberSeries(data.open.values,",
"attr, indic): if self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic",
"super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value)",
"\"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] =",
"= False def update_user_vars(self): # Update series defined by user if exist. try:",
"if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s in",
"name): return self.get_item(name) def update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar",
"datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar = -1 self._Helper = Helper self._series",
"Bar ) class DataContext(object): \"\"\" A DataContext expose data should be visited by",
"= self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec in technicals: if tec.is_multiple: for",
"indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if self.ith_comb",
"self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract)",
"else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value)",
"def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series): 序列变量",
"s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError:",
"__getattr__(self, name): return self.get_item(name) def update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar =",
"DataContext expose data should be visited by multiple strategie. which including bars of",
"data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value) def __getattr__(self, name): return",
"0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row def __len__(self): return len(self._Helper)",
"technicals and series of strategie. \"\"\" def __init__(self, Helper): data = Helper.data self.open",
"'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy = -1",
"else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data",
"(str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series): if",
"technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec",
"DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data = data def __setattr__(self, name, value): if",
"'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 #",
"self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar]",
"self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb",
"value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data if",
"self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self): # Update series defined by user",
"self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr",
"self.technicals = [[{}]] self._curbar = -1 self._Helper = Helper self._series = [[{}]] self._variables",
"else: self.add_variable(name, value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名",
"if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}])",
"-*- ## # @file data_context.py # @brief # @author wondereamer # @version 0.1",
"strategie. \"\"\" def __init__(self, Helper): data = Helper.data self.open = NumberSeries(data.open.values, 'open') self.close",
"add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb < len(self._all_variables):",
"for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar =",
"self.ith_strategy = -1 # 第j个策略 self.bar = Bar(None, None, None, None, None, None)",
"self.datetime[0] >= self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return",
"= Helper.data self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values,",
"+ 1 @property def pcontract(self): return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def",
"return data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value) def __getattr__(self, name):",
"raw_data(self): return self._Helper.data @property def curbar(self): return self._curbar + 1 @property def pcontract(self):",
"if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value)",
"@property def raw_data(self): return self._Helper.data @property def curbar(self): return self._curbar + 1 @property",
"NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1",
"return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if",
"'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name,",
"False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar = -1 self._Helper",
"for s in tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self):",
"quantity.digger.util import elogger as logger from quantity.digger.datastruct import ( Bar ) class DataContext(object):",
"indic): if self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else:",
"1, 1) self.technicals = [[{}]] self._curbar = -1 self._Helper = Helper self._series =",
"else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals): if self.ith_strategy",
"1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar",
"except IndexError: pass else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals",
"s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row,",
"if self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name:",
"!= 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row def __len__(self): return",
"= NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy",
"Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self): # Update",
"value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self, attr, s):",
"@author wondereamer # @version 0.1 # @date 2016-11-27 import datetime from quantity.digger.engine.series import",
"self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False def",
"self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals): if self.ith_strategy <",
"< len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self,",
"for tec in technicals: if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else: for",
"value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb < len(self._all_variables): if self.ith_strategy",
"= NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume =",
"tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not",
"of strategie. \"\"\" def __init__(self, Helper): data = Helper.data self.open = NumberSeries(data.open.values, 'open')",
"self.new_row: self.last_curbar -= 1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >=",
"return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def update_system_vars(self): # self.data = np.append(data,",
"self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data =",
"which including bars of specific PContract, technicals and series of strategie. \"\"\" def",
"technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec in technicals: if tec.is_multiple:",
"(Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]):",
"else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if self.ith_comb <",
"# Update series defined by user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except",
"( Bar ) class DataContext(object): \"\"\" A DataContext expose data should be visited",
"self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals):",
"None, None, None) self.new_row = False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals =",
"tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0],",
"data = Helper.data self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high =",
"and series of strategie. \"\"\" def __init__(self, Helper): data = Helper.data self.open =",
"self._Helper = Helper self._series = [[{}]] self._variables = [[{}]] self._all_variables = [[{}]] self._size",
"self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0],",
"series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except",
"data should be visited by multiple strategie. which including bars of specific PContract,",
"= [[{}]] self._variables = [[{}]] self._all_variables = [[{}]] self._size = len(data.close) @property def",
"class DataContext(object): \"\"\" A DataContext expose data should be visited by multiple strategie.",
"exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec in technicals:",
"from quantity.digger.util import elogger as logger from quantity.digger.datastruct import ( Bar ) class",
"contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name) def update_system_vars(self): # self.data =",
"for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist. try: technicals",
"self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb",
"获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO",
"self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row",
"Helper): data = Helper.data self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high",
"elogger as logger from quantity.digger.datastruct import ( Bar ) class DataContext(object): \"\"\" A",
"TechnicalBase from quantity.digger.util import elogger as logger from quantity.digger.datastruct import ( Bar )",
"@date 2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import",
"multiple strategie. which including bars of specific PContract, technicals and series of strategie.",
"< len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object):",
"self._all_variables = [[{}]] self._size = len(data.close) @property def raw_data(self): return self._Helper.data @property def",
"self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0],",
"= DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy = -1 # 第j个策略",
"attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([],",
"import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger as",
"len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase):",
"False def update_user_vars(self): # Update series defined by user if exist. try: series",
"if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for tec in",
"@TODO ... if self.ith_comb < len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value",
"get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。",
"try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s in series: s.update_curbar(self._curbar)",
"else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value,",
"add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series): 序列变量 \"\"\"",
"defined by user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else:",
"name, value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data",
"value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series):",
"self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def",
"var): if self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else:",
"self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0],",
"self._series = [[{}]] self._variables = [[{}]] self._all_variables = [[{}]] self._size = len(data.close) @property",
"strategie. which including bars of specific PContract, technicals and series of strategie. \"\"\"",
"be visited by multiple strategie. which including bars of specific PContract, technicals and",
"elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self, attr, s): \"\"\"",
"# @date 2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base",
"bars of specific PContract, technicals and series of strategie. \"\"\" def __init__(self, Helper):",
"self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb = -1 # 第i个组合",
"except IndexError: pass else: for tec in technicals: if tec.is_multiple: for s in",
"\"\"\" A DataContext expose data should be visited by multiple strategie. which including",
"# 第j个策略 self.bar = Bar(None, None, None, None, None, None) self.new_row = False",
"if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}])",
"self.new_row = False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar =",
"return self._curbar + 1 @property def pcontract(self): return self._Helper.pcontract @property def contract(self): return",
"pass else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist.",
"\"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if",
"None, None, None, None) self.new_row = False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals",
"Helper.data self.open = NumberSeries(data.open.values, 'open') self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high')",
"including bars of specific PContract, technicals and series of strategie. \"\"\" def __init__(self,",
"return self.get_item(name) def update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar)",
"pcontract(self): return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return self.get_item(name)",
"quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger",
"= -1 self._Helper = Helper self._series = [[{}]] self._variables = [[{}]] self._all_variables =",
"s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update technicals if exist. try: technicals =",
"def update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar)",
"1) self.technicals = [[{}]] self._curbar = -1 self._Helper = Helper self._series = [[{}]]",
"len(data.close) @property def raw_data(self): return self._Helper.data @property def curbar(self): return self._curbar + 1",
"of specific PContract, technicals and series of strategie. \"\"\" def __init__(self, Helper): data",
"< len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else:",
"def update_user_vars(self): # Update series defined by user if exist. try: series =",
"[[{}]] self._variables = [[{}]] self._all_variables = [[{}]] self._size = len(data.close) @property def raw_data(self):",
"self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s in series: s.update_curbar(self._curbar) s.duplicate_last_element() # Update",
"def raw_data(self): return self._Helper.data @property def curbar(self): return self._curbar + 1 @property def",
"# @file data_context.py # @brief # @author wondereamer # @version 0.1 # @date",
"= self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value) def __getattr__(self, name): return getattr(self.data,",
"< len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else:",
"[[{}]] self._size = len(data.close) @property def raw_data(self): return self._Helper.data @property def curbar(self): return",
"s.duplicate_last_element() # Update technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass",
"len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr:",
"quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger as logger from quantity.digger.datastruct import (",
"'open') self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low')",
"self.get_item(name) def update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar = self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar)",
"self.ith_comb = -1 # 第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar = Bar(None,",
"self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase):",
"tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar) def",
"indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if self.ith_comb < len(self._variables): if",
"[[{}]] self._all_variables = [[{}]] self._size = len(data.close) @property def raw_data(self): return self._Helper.data @property",
"add_variable(self, attr, var): if self.ith_comb < len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] =",
"as logger from quantity.digger.datastruct import ( Bar ) class DataContext(object): \"\"\" A DataContext",
"self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0])",
"def pcontract(self): return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def __getattr__(self, name): return",
"= self.last_curbar self.open.update_curbar(self._curbar) self.close.update_curbar(self._curbar) self.high.update_curbar(self._curbar) self.low.update_curbar(self._curbar) self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0],",
"curbar(self): return self._curbar + 1 @property def pcontract(self): return self._Helper.pcontract @property def contract(self):",
"self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class",
"value}) else: self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name,",
"self._variables = [[{}]] self._all_variables = [[{}]] self._size = len(data.close) @property def raw_data(self): return",
"= NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime = DateTimeSeries(data.index, 'datetime') self.ith_comb =",
"self._size = len(data.close) @property def raw_data(self): return self._Helper.data @property def curbar(self): return self._curbar",
"-*- coding: utf-8 -*- ## # @file data_context.py # @brief # @author wondereamer",
"self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False def update_user_vars(self): # Update series",
"self.add_variable(name, value) def add_series(self, attr, s): \"\"\" 添加on_init中初始化的序列变量 Args: attr (str): 属性名 s",
"pass else: for tec in technicals: if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar)",
"self.new_row def __len__(self): return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name]",
"@version 0.1 # @date 2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries",
"user if exist. try: series = self._series[self.ith_comb][self.ith_strategy].values() except IndexError: pass else: for s",
"= len(data.close) @property def raw_data(self): return self._Helper.data @property def curbar(self): return self._curbar +",
"self.close = NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume",
"# Update technicals if exist. try: technicals = self.technicals[self.ith_comb][self.ith_strategy].values() except IndexError: pass else:",
"self.volume[0]) self.new_row = False def update_user_vars(self): # Update series defined by user if",
"from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger as logger from quantity.digger.datastruct import",
"# @author wondereamer # @version 0.1 # @date 2016-11-27 import datetime from quantity.digger.engine.series",
"self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else: self.add_variable(name, value) def add_series(self, attr,",
"data def __setattr__(self, name, value): if name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return",
"= False self.next_datetime = datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar = -1",
"return self._Helper.data @property def curbar(self): return self._curbar + 1 @property def pcontract(self): return",
"in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if",
"Args: attr (str): 属性名 s (Series): 序列变量 \"\"\" s.reset_data([], self._size) if self.ith_comb <",
"s.reset_data([], self._size) if self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s",
"self._all_variables.append([{name: value}]) if isinstance(value, SeriesBase): self.add_series(name, value) elif isinstance(value, TechnicalBase): self.add_indicator(name, value) else:",
"value) return data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value) def __getattr__(self,",
"technicals: if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series:",
"NumberSeries(data.close.values, 'close') self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values,",
"'datetime') self.ith_comb = -1 # 第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar =",
"self.volume.update_curbar(self._curbar) self.datetime.update_curbar(self._curbar) self.bar = Bar(self.datetime[0], self.open[0], self.close[0], self.high[0], self.low[0], self.volume[0]) self.new_row = False",
"if self.datetime[0] >= self.next_datetime and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise",
"self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if self.ith_comb < len(self._variables):",
"and self.curbar != 0: logger.error('合约[%s] 数据时间逆序或冗余' % self.pcontract) raise return True, self.new_row def",
"len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\"",
"add_indicator(self, attr, indic): if self.ith_comb < len(self.technicals): if self.ith_strategy < len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] =",
"self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def",
"\"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar -= 1",
"\"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" #",
"if not self.new_row: self.last_curbar -= 1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if",
"self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if self.ith_comb < len(self._variables): if self.ith_strategy <",
"var}) else: self._variables.append([{attr: var}]) class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data = data",
"def add_item(self, name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb <",
"= -1 # 第i个组合 self.ith_strategy = -1 # 第j个策略 self.bar = Bar(None, None,",
"len(self.technicals[self.ith_comb]): self.technicals[self.ith_comb][self.ith_strategy][attr] = indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr,",
"= [[{}]] self._size = len(data.close) @property def raw_data(self): return self._Helper.data @property def curbar(self):",
"< len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else:",
"name == 'data': super(DataContextAttributeHelper, self).__setattr__(name, value) return data = self.data if name in",
"0.1 # @date 2016-11-27 import datetime from quantity.digger.engine.series import SeriesBase, NumberSeries, DateTimeSeries from",
"= NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime =",
"'close') self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume')",
"= indic else: self.technicals[self.ith_comb].append({attr: indic}) else: self.technicals.append([{attr: indic}]) def add_variable(self, attr, var): if",
"DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger as logger from quantity.digger.datastruct",
"self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s})",
"SeriesBase, NumberSeries, DateTimeSeries from quantity.digger.technicals.base import TechnicalBase from quantity.digger.util import elogger as logger",
"def __len__(self): return len(self._Helper) def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def",
"if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name: value}])",
"class DataContextAttributeHelper(object): \"\"\"\"\"\" def __init__(self, data): self.data = data def __setattr__(self, name, value):",
"self.high = NumberSeries(data.high.values, 'high') self.low = NumberSeries(data.low.values, 'low') self.volume = NumberSeries(data.volume.values, 'volume') self.datetime",
"self._size) if self.ith_comb < len(self._series): if self.ith_strategy < len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else:",
"def get_item(self, name): \"\"\" 获取用户在策略on_init函数中初始化的变量 \"\"\" return self._all_variables[self.ith_comb][self.ith_strategy][name] def add_item(self, name, value): \"\"\"",
"= [[{}]] self._curbar = -1 self._Helper = Helper self._series = [[{}]] self._variables =",
"in tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。",
"def __init__(self, data): self.data = data def __setattr__(self, name, value): if name ==",
"self.last_curbar -= 1 return False, None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime",
"name, value): \"\"\" 添加用户初始化的变量。 \"\"\" # @TODO ... if self.ith_comb < len(self._all_variables): if",
"s.update_curbar(self._curbar) def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row:",
"len(self._all_variables): if self.ith_strategy < len(self._all_variables[self.ith_comb]): self._all_variables[self.ith_comb][self.ith_strategy][name] = value else: self._all_variables[self.ith_comb].append({name: value}) else: self._all_variables.append([{name:",
"< len(self._variables): if self.ith_strategy < len(self._variables[self.ith_comb]): self._variables[self.ith_comb][self.ith_strategy][attr] = var else: self._variables[self.ith_comb].append({attr: var}) else:",
"if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else: for s in tec.series: s.update_curbar(self._curbar)",
"@property def curbar(self): return self._curbar + 1 @property def pcontract(self): return self._Helper.pcontract @property",
"def rolling_forward(self): \"\"\" 滚动读取下一步的数据。 \"\"\" self.new_row, self.last_curbar = self._Helper.rolling_forward() if not self.new_row: self.last_curbar",
"1 @property def pcontract(self): return self._Helper.pcontract @property def contract(self): return self._Helper.pcontract.contract def __getattr__(self,",
"self).__setattr__(name, value) return data = self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value) def",
"def __getattr__(self, name): return self.get_item(name) def update_system_vars(self): # self.data = np.append(data, tracker.container_day) self._curbar",
"tec in technicals: if tec.is_multiple: for s in tec.series.values(): s.update_curbar(self._curbar) else: for s",
"= datetime.datetime(2100, 1, 1) self.technicals = [[{}]] self._curbar = -1 self._Helper = Helper",
"expose data should be visited by multiple strategie. which including bars of specific",
"-1 self._Helper = Helper self._series = [[{}]] self._variables = [[{}]] self._all_variables = [[{}]]",
"s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic): if self.ith_comb",
"self.data if name in data._all_variables[data.ith_comb][data.ith_strategy]: data.add_item(name, value) def __getattr__(self, name): return getattr(self.data, name)",
"self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self, attr, indic):",
"Bar(None, None, None, None, None, None) self.new_row = False self.next_datetime = datetime.datetime(2100, 1,",
"None self.next_datetime = self._Helper.data.index[self.last_curbar] if self.datetime[0] >= self.next_datetime and self.curbar != 0: logger.error('合约[%s]",
"< len(self._series[self.ith_comb]): self._series[self.ith_comb][self.ith_strategy][attr] = s else: self._series[self.ith_comb].append({attr: s}) else: self._series.append([{attr: s}]) def add_indicator(self,"
] |
[
"# the data, split between train and test sets (x_train, y_train), (x_test, y_test)",
"verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:',",
"tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count = {'CPU'",
"keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu',",
"1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train",
"= {'CPU' : num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction =",
"Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size",
"\"1\" import tensorflow as tf ## 1. simple setup of default tensorflow session",
"a lot of margin for parameter tuning). 16 seconds per epoch on a",
"model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten())",
"os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow",
"(1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0],",
"optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test,",
"test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train",
"num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ #",
"import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from",
"'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train,",
"= 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True,",
"convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test =",
"128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols",
"print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class",
"True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from keras import backend as K",
"from keras import backend as K batch_size = 128 num_classes = 10 epochs",
"os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as",
"convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs",
"0.55 sess = tf.Session(config=tf_config) from keras import backend as K K.set_session(sess) import keras",
"sess = tf.Session(config=tf_config) from keras import backend as K K.set_session(sess) import keras from",
"as K batch_size = 128 num_classes = 10 epochs = 12 # input",
"2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train,",
"__future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"]",
"class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test,",
"tuning). 16 seconds per epoch on a GRID K520 GPU. ''' from __future__",
"= \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf",
"input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes,",
": num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess",
"vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes)",
"x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape)",
"img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else:",
"samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train",
"tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config) ## 2.",
"a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after",
"epochs (there is still a lot of margin for parameter tuning). 16 seconds",
"x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape",
"activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score =",
"1 else: num_GPU = 0 num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\",
"= 12 # input image dimensions img_rows, img_cols = 28, 28 # the",
"mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test =",
"tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from keras import backend as K K.set_session(sess)",
"model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test,",
"len(v)>0]) if GPU > 0: num_GPU = 1 num_CPU = 1 else: num_GPU",
"x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0],",
"(x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0],",
"Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25))",
"import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] =",
"## 1. simple setup of default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) #",
"from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras",
"activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])",
"from keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size =",
"'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)",
"for parameter tuning). 16 seconds per epoch on a GRID K520 GPU. '''",
"255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples')",
"keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten",
"GPU. ''' from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see",
"# tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config) ## 2. more strategy setup",
"model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test",
"= 1 GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU",
"v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0: num_GPU = 1 num_CPU",
"GRID K520 GPU. ''' from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"",
"session num_cores = 1 GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0])",
"inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count = {'CPU' : num_CPU, 'GPU'",
"in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0: num_GPU = 1 num_CPU =",
"num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from keras",
"img_rows, img_cols = 28, 28 # the data, split between train and test",
"x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') #",
"model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train,",
"img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows,",
"if len(v)>0]) if GPU > 0: num_GPU = 1 num_CPU = 1 else:",
"x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples')",
"backend as K K.set_session(sess) import keras from keras.datasets import mnist from keras.models import",
"img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test =",
"epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 #",
"for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0: num_GPU = 1",
"28 # the data, split between train and test sets (x_train, y_train), (x_test,",
"img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols,",
"as tf ## 1. simple setup of default tensorflow session # tf_config =",
"binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model =",
"= (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test =",
"model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2,",
"keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D,",
"1. simple setup of default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth",
"is still a lot of margin for parameter tuning). 16 seconds per epoch",
"num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess =",
"3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu'))",
"tf.Session(config=tf_config) ## 2. more strategy setup of default tensorflow session num_cores = 1",
"else: num_GPU = 0 num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores,",
"<reponame>llv22/keras '''Trains a simple convnet on the MNIST dataset. Gets to 99.25% test",
"parameter tuning). 16 seconds per epoch on a GRID K520 GPU. ''' from",
"0 num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\",
"= x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train =",
"x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0],",
"setup of default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True",
"print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"",
"= 1 else: num_GPU = 0 num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores,",
"# convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test",
"(x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows,",
"img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols)",
"test accuracy after 12 epochs (there is still a lot of margin for",
"the data, split between train and test sets (x_train, y_train), (x_test, y_test) =",
"keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense,",
"/= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert",
"metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0)",
"between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format()",
"= keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),",
"model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,",
"tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess",
"issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf ## 1. simple setup",
"MaxPooling2D from keras import backend as K batch_size = 128 num_classes = 10",
"1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train",
"intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count = {'CPU' :",
"model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))",
"import backend as K batch_size = 128 num_classes = 10 epochs = 12",
"> 0: num_GPU = 1 num_CPU = 1 else: num_GPU = 0 num_CPU",
"keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import",
"default tensorflow session num_cores = 1 GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',')",
"= 28, 28 # the data, split between train and test sets (x_train,",
"activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5))",
"data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data()",
"num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))",
"12 epochs (there is still a lot of margin for parameter tuning). 16",
"= Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2)))",
"# sess = tf.Session(config=tf_config) ## 2. more strategy setup of default tensorflow session",
"1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows,",
"os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0: num_GPU = 1 num_CPU = 1",
"input image dimensions img_rows, img_cols = 28, 28 # the data, split between",
"model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1,",
"shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to",
"'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices",
"{'CPU' : num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55",
"if GPU > 0: num_GPU = 1 num_CPU = 1 else: num_GPU =",
"y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64,",
"x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1,",
"y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)",
"of default tensorflow session num_cores = 1 GPU = len([v for v in",
"class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential()",
"accuracy after 12 epochs (there is still a lot of margin for parameter",
"y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1,",
"# input image dimensions img_rows, img_cols = 28, 28 # the data, split",
"on the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there",
"K K.set_session(sess) import keras from keras.datasets import mnist from keras.models import Sequential from",
"# see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf ## 1.",
"= x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train",
"GPU > 0: num_GPU = 1 num_CPU = 1 else: num_GPU = 0",
"12 # input image dimensions img_rows, img_cols = 28, 28 # the data,",
"99.25% test accuracy after 12 epochs (there is still a lot of margin",
"and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first':",
"allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count = {'CPU' : num_CPU, 'GPU' : num_GPU}",
"x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary",
"1 num_CPU = 1 else: num_GPU = 0 num_CPU = 1 tf_config =",
"simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12",
"setup of default tensorflow session num_cores = 1 GPU = len([v for v",
"validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1])",
"x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape",
"0.1 # sess = tf.Session(config=tf_config) ## 2. more strategy setup of default tensorflow",
"x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0],",
"from keras import backend as K K.set_session(sess) import keras from keras.datasets import mnist",
"from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import",
"more strategy setup of default tensorflow session num_cores = 1 GPU = len([v",
"1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\",
"on a GRID K520 GPU. ''' from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"]",
"= True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from keras import backend as",
"''' from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue",
"lot of margin for parameter tuning). 16 seconds per epoch on a GRID",
"len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0: num_GPU =",
"= 0.1 # sess = tf.Session(config=tf_config) ## 2. more strategy setup of default",
"tf ## 1. simple setup of default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True)",
"y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3,",
"batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions",
"import Conv2D, MaxPooling2D from keras import backend as K batch_size = 128 num_classes",
"y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:',",
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf ## 1. simple setup of default",
"log_device_placement=True, \\ device_count = {'CPU' : num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth =",
"import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D",
"# tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 #",
"img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1)",
"input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /=",
"import backend as K K.set_session(sess) import keras from keras.datasets import mnist from keras.models",
"16 seconds per epoch on a GRID K520 GPU. ''' from __future__ import",
"= keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3,",
"Gets to 99.25% test accuracy after 12 epochs (there is still a lot",
"Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as",
"the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is",
"to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model",
"model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size,",
"num_cores = 1 GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if",
"per epoch on a GRID K520 GPU. ''' from __future__ import print_function import",
"= 1 num_CPU = 1 else: num_GPU = 0 num_CPU = 1 tf_config",
"input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test",
"keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3),",
"image dimensions img_rows, img_cols = 28, 28 # the data, split between train",
"tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from keras import backend",
"import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import",
"model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score",
"/= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test",
"= len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0: num_GPU",
"Conv2D, MaxPooling2D from keras import backend as K batch_size = 128 num_classes =",
"= tf.Session(config=tf_config) from keras import backend as K K.set_session(sess) import keras from keras.datasets",
"#152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf ## 1. simple setup of",
"== 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows,",
"img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)",
"= True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config) ## 2. more",
"0: num_GPU = 1 num_CPU = 1 else: num_GPU = 0 num_CPU =",
"255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class",
"num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu'))",
"Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from",
"seconds per epoch on a GRID K520 GPU. ''' from __future__ import print_function",
"epoch on a GRID K520 GPU. ''' from __future__ import print_function import os",
"img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32')",
"= x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:',",
"tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction =",
"1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows,",
"print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train =",
"img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /=",
"= x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape =",
"device_count = {'CPU' : num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction",
"\"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf ##",
"img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols,",
"sess = tf.Session(config=tf_config) ## 2. more strategy setup of default tensorflow session num_cores",
"margin for parameter tuning). 16 seconds per epoch on a GRID K520 GPU.",
"\\ # log_device_placement=True, \\ device_count = {'CPU' : num_CPU, 'GPU' : num_GPU} )",
"model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax'))",
"= 0.55 sess = tf.Session(config=tf_config) from keras import backend as K K.set_session(sess) import",
"2. more strategy setup of default tensorflow session num_cores = 1 GPU =",
"activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test,",
"\\ device_count = {'CPU' : num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True",
"split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if",
"keras import backend as K batch_size = 128 num_classes = 10 epochs =",
"K batch_size = 128 num_classes = 10 epochs = 12 # input image",
"= mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test",
"3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(),",
"still a lot of margin for parameter tuning). 16 seconds per epoch on",
"= x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape =",
"dimensions img_rows, img_cols = 28, 28 # the data, split between train and",
"from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152",
"1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255",
"'''Trains a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy",
"x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train",
"print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors",
"tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config)",
"simple setup of default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth =",
"img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols,",
"= 128 num_classes = 10 epochs = 12 # input image dimensions img_rows,",
"tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count",
"kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128,",
"= \"1\" import tensorflow as tf ## 1. simple setup of default tensorflow",
"\\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count = {'CPU' : num_CPU, 'GPU' :",
"= tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess =",
"num_GPU = 0 num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\",
"num_GPU = 1 num_CPU = 1 else: num_GPU = 0 num_CPU = 1",
"x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train =",
"of default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True #",
"epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test",
"strategy setup of default tensorflow session num_cores = 1 GPU = len([v for",
"= tf.Session(config=tf_config) ## 2. more strategy setup of default tensorflow session num_cores =",
"sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train =",
"# log_device_placement=True, \\ device_count = {'CPU' : num_CPU, 'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth",
"of margin for parameter tuning). 16 seconds per epoch on a GRID K520",
"if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0],",
"# tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config) ##",
"True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config) ## 2. more strategy",
"tf.Session(config=tf_config) from keras import backend as K K.set_session(sess) import keras from keras.datasets import",
"= (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255",
"import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend",
"train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() ==",
"(there is still a lot of margin for parameter tuning). 16 seconds per",
"samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes)",
"= 10 epochs = 12 # input image dimensions img_rows, img_cols = 28,",
"tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 # sess = tf.Session(config=tf_config) ## 2. more strategy setup of",
"import tensorflow as tf ## 1. simple setup of default tensorflow session #",
"= tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count =",
"K.set_session(sess) import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers",
"10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28",
"## 2. more strategy setup of default tensorflow session num_cores = 1 GPU",
"dataset. Gets to 99.25% test accuracy after 12 epochs (there is still a",
"a GRID K520 GPU. ''' from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] =",
"\\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True, \\ # log_device_placement=True, \\ device_count = {'CPU' : num_CPU,",
") tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from keras import",
"keras import backend as K K.set_session(sess) import keras from keras.datasets import mnist from",
"num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols =",
"Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K",
"session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1",
"img_cols = 28, 28 # the data, split between train and test sets",
"x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train",
"28, 28 # the data, split between train and test sets (x_train, y_train),",
"tensorflow session num_cores = 1 GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if",
"x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test",
"'GPU' : num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config)",
": num_GPU} ) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.55 sess = tf.Session(config=tf_config) from",
"see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" import tensorflow as tf ## 1. simple",
"(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy,",
"mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers",
"K520 GPU. ''' from __future__ import print_function import os os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" #",
"1 GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU >",
"K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1,",
"GPU = len([v for v in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(',') if len(v)>0]) if GPU > 0:",
"backend as K batch_size = 128 num_classes = 10 epochs = 12 #",
"from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout,",
"batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0])",
"else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)",
"= 0 num_CPU = 1 tf_config = tf.ConfigProto( intra_op_parallelism_threads=num_cores, \\ inter_op_parallelism_threads=num_cores, \\ allow_soft_placement=True,",
"num_CPU = 1 else: num_GPU = 0 num_CPU = 1 tf_config = tf.ConfigProto(",
"(img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test",
"after 12 epochs (there is still a lot of margin for parameter tuning).",
"tensorflow as tf ## 1. simple setup of default tensorflow session # tf_config",
"to 99.25% test accuracy after 12 epochs (there is still a lot of",
"keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size = 128",
"x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows,",
"as K K.set_session(sess) import keras from keras.datasets import mnist from keras.models import Sequential",
"import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import",
"MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is still",
"matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32,",
"default tensorflow session # tf_config = tf.ConfigProto(log_device_placement=True) # tf_config.gpu_options.allow_growth = True # tf_config.gpu_options.per_process_gpu_memory_fraction",
"= x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32')"
] |
[
"network import network from theano import tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\",",
"= T._shared(param.get_value()) new_params.append(param) params = new_params new_network = network(batch_size=None, params = params) print",
"in params: param = T._shared(param.get_value()) new_params.append(param) params = new_params new_network = network(batch_size=None, params",
"param = T._shared(param.get_value()) new_params.append(param) params = new_params new_network = network(batch_size=None, params = params)",
"from network import network from theano import tensor as T parser = argparse.ArgumentParser()",
"run on a CPU.\") args = parser.parse_args() print \"loading model...\" f = file(args.source,",
"as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params from.\")",
"old_network.params if args.cpu: print \"converting gpu parameters...\" new_params=[] for param in params: param",
"\"loading model...\" f = file(args.source, 'rb') old_network = cPickle.load(f) f.close() params = old_network.params",
"action='store_const', const=True, default=False, help=\"Convert network to run on a CPU.\") args = parser.parse_args()",
"model...\" f = file(args.source, 'rb') old_network = cPickle.load(f) f.close() params = old_network.params if",
"new_params=[] for param in params: param = T._shared(param.get_value()) new_params.append(param) params = new_params new_network",
"import network from theano import tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str,",
"import * from network import network from theano import tensor as T parser",
"parser.add_argument(\"dest\", type=str, help=\"File to place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True,",
"parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to run on a CPU.\")",
"gpu parameters...\" new_params=[] for param in params: param = T._shared(param.get_value()) new_params.append(param) params =",
"help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new network",
"f.close() params = old_network.params if args.cpu: print \"converting gpu parameters...\" new_params=[] for param",
"argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to",
"parser.parse_args() print \"loading model...\" f = file(args.source, 'rb') old_network = cPickle.load(f) f.close() params",
"import cPickle import argparse from inputFormat import * from network import network from",
"inputFormat import * from network import network from theano import tensor as T",
"params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\",",
"help=\"File to place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert",
"help=\"Convert network to run on a CPU.\") args = parser.parse_args() print \"loading model...\"",
"cPickle import argparse from inputFormat import * from network import network from theano",
"from theano import tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network",
"dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to run on a CPU.\") args =",
"\"converting gpu parameters...\" new_params=[] for param in params: param = T._shared(param.get_value()) new_params.append(param) params",
"= network(batch_size=None, params = params) print \"saving model...\" f = file(args.dest, 'wb') cPickle.dump(new_network,",
"from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const',",
"for param in params: param = T._shared(param.get_value()) new_params.append(param) params = new_params new_network =",
"network to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new network in.\")",
"import argparse from inputFormat import * from network import network from theano import",
"tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params",
"cPickle.load(f) f.close() params = old_network.params if args.cpu: print \"converting gpu parameters...\" new_params=[] for",
"* from network import network from theano import tensor as T parser =",
"new_params new_network = network(batch_size=None, params = params) print \"saving model...\" f = file(args.dest,",
"type=str, help=\"File to place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False,",
"parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place",
"print \"loading model...\" f = file(args.source, 'rb') old_network = cPickle.load(f) f.close() params =",
"argparse from inputFormat import * from network import network from theano import tensor",
"params: param = T._shared(param.get_value()) new_params.append(param) params = new_params new_network = network(batch_size=None, params =",
"import tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal",
"to run on a CPU.\") args = parser.parse_args() print \"loading model...\" f =",
"to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new network in.\") parser.add_argument(\"--cpu\",",
"f = file(args.source, 'rb') old_network = cPickle.load(f) f.close() params = old_network.params if args.cpu:",
"CPU.\") args = parser.parse_args() print \"loading model...\" f = file(args.source, 'rb') old_network =",
"new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to run",
"network(batch_size=None, params = params) print \"saving model...\" f = file(args.dest, 'wb') cPickle.dump(new_network, f,",
"file(args.source, 'rb') old_network = cPickle.load(f) f.close() params = old_network.params if args.cpu: print \"converting",
"= new_params new_network = network(batch_size=None, params = params) print \"saving model...\" f =",
"from inputFormat import * from network import network from theano import tensor as",
"parameters...\" new_params=[] for param in params: param = T._shared(param.get_value()) new_params.append(param) params = new_params",
"network to run on a CPU.\") args = parser.parse_args() print \"loading model...\" f",
"on a CPU.\") args = parser.parse_args() print \"loading model...\" f = file(args.source, 'rb')",
"T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\",",
"network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to run on",
"= argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File",
"const=True, default=False, help=\"Convert network to run on a CPU.\") args = parser.parse_args() print",
"new_network = network(batch_size=None, params = params) print \"saving model...\" f = file(args.dest, 'wb')",
"if args.cpu: print \"converting gpu parameters...\" new_params=[] for param in params: param =",
"T._shared(param.get_value()) new_params.append(param) params = new_params new_network = network(batch_size=None, params = params) print \"saving",
"theano import tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to",
"type=str, help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new",
"= old_network.params if args.cpu: print \"converting gpu parameters...\" new_params=[] for param in params:",
"<reponame>gauthamv529/Neurohex import cPickle import argparse from inputFormat import * from network import network",
"args = parser.parse_args() print \"loading model...\" f = file(args.source, 'rb') old_network = cPickle.load(f)",
"param in params: param = T._shared(param.get_value()) new_params.append(param) params = new_params new_network = network(batch_size=None,",
"args.cpu: print \"converting gpu parameters...\" new_params=[] for param in params: param = T._shared(param.get_value())",
"to place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network",
"default=False, help=\"Convert network to run on a CPU.\") args = parser.parse_args() print \"loading",
"'rb') old_network = cPickle.load(f) f.close() params = old_network.params if args.cpu: print \"converting gpu",
"= cPickle.load(f) f.close() params = old_network.params if args.cpu: print \"converting gpu parameters...\" new_params=[]",
"\"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to run on a CPU.\") args",
"print \"converting gpu parameters...\" new_params=[] for param in params: param = T._shared(param.get_value()) new_params.append(param)",
"parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled network to steal params from.\") parser.add_argument(\"dest\", type=str,",
"= file(args.source, 'rb') old_network = cPickle.load(f) f.close() params = old_network.params if args.cpu: print",
"params = params) print \"saving model...\" f = file(args.dest, 'wb') cPickle.dump(new_network, f, protocol=cPickle.HIGHEST_PROTOCOL)",
"place new network in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to",
"new_params.append(param) params = new_params new_network = network(batch_size=None, params = params) print \"saving model...\"",
"a CPU.\") args = parser.parse_args() print \"loading model...\" f = file(args.source, 'rb') old_network",
"old_network = cPickle.load(f) f.close() params = old_network.params if args.cpu: print \"converting gpu parameters...\"",
"network from theano import tensor as T parser = argparse.ArgumentParser() parser.add_argument(\"source\", type=str, help=\"Pickled",
"params = old_network.params if args.cpu: print \"converting gpu parameters...\" new_params=[] for param in",
"steal params from.\") parser.add_argument(\"dest\", type=str, help=\"File to place new network in.\") parser.add_argument(\"--cpu\", \"-c\",",
"= params) print \"saving model...\" f = file(args.dest, 'wb') cPickle.dump(new_network, f, protocol=cPickle.HIGHEST_PROTOCOL) f.close()",
"= parser.parse_args() print \"loading model...\" f = file(args.source, 'rb') old_network = cPickle.load(f) f.close()",
"in.\") parser.add_argument(\"--cpu\", \"-c\", dest=\"cpu\", action='store_const', const=True, default=False, help=\"Convert network to run on a",
"params = new_params new_network = network(batch_size=None, params = params) print \"saving model...\" f"
] |
[
"= Counter() for (start, end) in vents: vent_points.update(points_between(start, end)) return sum(1 for (_,",
"the vents. ''' vents = [] for line in lines: start, _, end",
"y) x += x_step y += y_step yield Point(x, y) def sign(value: int)",
"2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def test_part1_example(self): self.assertEqual(part1(self.data),",
"lines: start, _, end = line.split() p1_x, p1_y = start.split(',') p2_x, p2_y =",
"vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example test cases for",
"y) def sign(value: int) -> int: ''' Returns the sign of value, i.e.",
"<https://adventofcode.com/2021/day/5> ''' from collections import Counter from dataclasses import dataclass from typing import",
"either vertical, horizontal, or 45 degrees. ''' x_step = sign(end.x - start.x) y_step",
"[ '0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1',",
"for Day 5, part 1 ''' vents = parse_input(lines) vent_points: Counter = Counter()",
"-> int: ''' Returns the sign of value, i.e. 1 if value is",
"parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents: if start.x ==",
"''' x: int y: int def points_between(start: Point, end: Point) -> Iterable[Point]: '''",
"''' Solvers and example test cases for Day 5 of the Advent of",
"Point) tuples describing the vents. ''' vents = [] for line in lines:",
"''' if value < 0: return -1 if value == 0: return 0",
"for line in lines: start, _, end = line.split() p1_x, p1_y = start.split(',')",
"_, end = line.split() p1_x, p1_y = start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x),",
"sum(1 for (_, count) in vent_points.most_common() if count >= 2) def part2(lines: Iterable[str])",
"return 0 return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the",
"end) in vents: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if",
"Day 5, part 1 ''' vents = parse_input(lines) vent_points: Counter = Counter() for",
"== 0: return 0 return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: '''",
"count >= 2) def part2(lines: Iterable[str]) -> int: ''' Solver for Day 5,",
"return sum(1 for (_, count) in vent_points.most_common() if count >= 2) def part2(lines:",
"Solver for Day 5, part 2 ''' vents = parse_input(lines) vent_points: Counter =",
"for Day 5, part 2 ''' vents = parse_input(lines) vent_points: Counter = Counter()",
"count >= 2) @dataclass(frozen=True) class Point: ''' Represents a single (x, y) coordinate.",
"yield Point(x, y) def sign(value: int) -> int: ''' Returns the sign of",
"-> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 ->",
"Line must be either vertical, horizontal, or 45 degrees. ''' x_step = sign(end.x",
"''' Parses the problem input and returns a list of (Point, Point) tuples",
"if start.x == end.x or start.y == end.y: vent_points.update(points_between(start, end)) return sum(1 for",
"int y: int def points_between(start: Point, end: Point) -> Iterable[Point]: ''' Iterates over",
"p1_x, p1_y = start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return",
"1 ''' vents = parse_input(lines) vent_points: Counter = Counter() for (start, end) in",
"end (inclusive). Line must be either vertical, horizontal, or 45 degrees. ''' x_step",
"part2(lines: Iterable[str]) -> int: ''' Solver for Day 5, part 2 ''' vents",
"Example test cases for Day 5, as specified in the problem description '''",
"start, _, end = line.split() p1_x, p1_y = start.split(',') p2_x, p2_y = end.split(',')",
"typing import Iterable, List, Tuple import unittest def part1(lines: Iterable[str]) -> int: '''",
"end: Point) -> Iterable[Point]: ''' Iterates over the integral points between start and",
"y != end.y: yield Point(x, y) x += x_step y += y_step yield",
"integral points between start and end (inclusive). Line must be either vertical, horizontal,",
"vents: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if count >=",
"= sign(end.x - start.x) y_step = sign(end.y - start.y) x = start.x y",
"end.y: yield Point(x, y) x += x_step y += y_step yield Point(x, y)",
"negative, or 0 if value is zero. ''' if value < 0: return",
"-> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 ->",
"class TestDay05(unittest.TestCase): ''' Example test cases for Day 5, as specified in the",
"5 of the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections",
"test cases for Day 5 of the Advent of Code 2021. Problem description:",
"Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter from dataclasses import dataclass from",
"0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0',",
"class Point: ''' Represents a single (x, y) coordinate. ''' x: int y:",
"''' Represents a single (x, y) coordinate. ''' x: int y: int def",
"Point) -> Iterable[Point]: ''' Iterates over the integral points between start and end",
"specified in the problem description ''' # pylint: disable=missing-function-docstring def setUp(self): self.data =",
"/usr/bin/env python ''' Solvers and example test cases for Day 5 of the",
"single (x, y) coordinate. ''' x: int y: int def points_between(start: Point, end:",
"Day 5, as specified in the problem description ''' # pylint: disable=missing-function-docstring def",
">= 2) def part2(lines: Iterable[str]) -> int: ''' Solver for Day 5, part",
"Point(x, y) x += x_step y += y_step yield Point(x, y) def sign(value:",
"p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example",
"Tuple import unittest def part1(lines: Iterable[str]) -> int: ''' Solver for Day 5,",
"= parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents: if start.x",
"- start.x) y_step = sign(end.y - start.y) x = start.x y = start.y",
"2) def part2(lines: Iterable[str]) -> int: ''' Solver for Day 5, part 2",
"0: return 0 return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses",
"cases for Day 5 of the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5>",
"Counter() for (start, end) in vents: if start.x == end.x or start.y ==",
"description ''' # pylint: disable=missing-function-docstring def setUp(self): self.data = [ '0,9 -> 5,9',",
"-> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 ->",
"'3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def test_part1_example(self): self.assertEqual(part1(self.data), 5)",
"return vents class TestDay05(unittest.TestCase): ''' Example test cases for Day 5, as specified",
"import Counter from dataclasses import dataclass from typing import Iterable, List, Tuple import",
"if value is negative, or 0 if value is zero. ''' if value",
"line in lines: start, _, end = line.split() p1_x, p1_y = start.split(',') p2_x,",
"-> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 ->",
"1 if value is positive, -1 if value is negative, or 0 if",
"from typing import Iterable, List, Tuple import unittest def part1(lines: Iterable[str]) -> int:",
"vents = parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents: vent_points.update(points_between(start,",
"-> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def test_part1_example(self): self.assertEqual(part1(self.data), 5) def",
"(start, end) in vents: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common()",
"dataclass from typing import Iterable, List, Tuple import unittest def part1(lines: Iterable[str]) ->",
"coordinate. ''' x: int y: int def points_between(start: Point, end: Point) -> Iterable[Point]:",
"vent_points: Counter = Counter() for (start, end) in vents: vent_points.update(points_between(start, end)) return sum(1",
"for (_, count) in vent_points.most_common() if count >= 2) @dataclass(frozen=True) class Point: '''",
"start and end (inclusive). Line must be either vertical, horizontal, or 45 degrees.",
"vents = [] for line in lines: start, _, end = line.split() p1_x,",
"2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter from dataclasses import dataclass",
"vents: if start.x == end.x or start.y == end.y: vent_points.update(points_between(start, end)) return sum(1",
"x = start.x y = start.y while x != end.x or y !=",
"def points_between(start: Point, end: Point) -> Iterable[Point]: ''' Iterates over the integral points",
"Counter = Counter() for (start, end) in vents: vent_points.update(points_between(start, end)) return sum(1 for",
"in lines: start, _, end = line.split() p1_x, p1_y = start.split(',') p2_x, p2_y",
"parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents: vent_points.update(points_between(start, end)) return",
"'9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9",
"start.x y = start.y while x != end.x or y != end.y: yield",
"7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8',",
"vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if count >= 2)",
"end = line.split() p1_x, p1_y = start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)),",
"start.y == end.y: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if",
"value == 0: return 0 return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]:",
"Iterable[str]) -> int: ''' Solver for Day 5, part 1 ''' vents =",
"sign(end.x - start.x) y_step = sign(end.y - start.y) x = start.x y =",
"''' vents = [] for line in lines: start, _, end = line.split()",
"-1 if value is negative, or 0 if value is zero. ''' if",
"for (start, end) in vents: if start.x == end.x or start.y == end.y:",
"for Day 5, as specified in the problem description ''' # pylint: disable=missing-function-docstring",
"Solver for Day 5, part 1 ''' vents = parse_input(lines) vent_points: Counter =",
"describing the vents. ''' vents = [] for line in lines: start, _,",
"0: return -1 if value == 0: return 0 return 1 def parse_input(lines:",
"2 ''' vents = parse_input(lines) vent_points: Counter = Counter() for (start, end) in",
"and returns a list of (Point, Point) tuples describing the vents. ''' vents",
"as specified in the problem description ''' # pylint: disable=missing-function-docstring def setUp(self): self.data",
"== end.y: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if count",
"y_step = sign(end.y - start.y) x = start.x y = start.y while x",
"'0,0 -> 8,8', '5,5 -> 8,2'] def test_part1_example(self): self.assertEqual(part1(self.data), 5) def test_part2_example(self): self.assertEqual(part2(self.data),",
"-> int: ''' Solver for Day 5, part 1 ''' vents = parse_input(lines)",
"sum(1 for (_, count) in vent_points.most_common() if count >= 2) @dataclass(frozen=True) class Point:",
"# pylint: disable=missing-function-docstring def setUp(self): self.data = [ '0,9 -> 5,9', '8,0 ->",
"return sum(1 for (_, count) in vent_points.most_common() if count >= 2) @dataclass(frozen=True) class",
"int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example test cases for Day 5, as",
"if count >= 2) @dataclass(frozen=True) class Point: ''' Represents a single (x, y)",
"def part2(lines: Iterable[str]) -> int: ''' Solver for Day 5, part 2 '''",
"example test cases for Day 5 of the Advent of Code 2021. Problem",
"List[Tuple[Point, Point]]: ''' Parses the problem input and returns a list of (Point,",
"tuples describing the vents. ''' vents = [] for line in lines: start,",
"def setUp(self): self.data = [ '0,9 -> 5,9', '8,0 -> 0,8', '9,4 ->",
"-> int: ''' Solver for Day 5, part 2 ''' vents = parse_input(lines)",
"be either vertical, horizontal, or 45 degrees. ''' x_step = sign(end.x - start.x)",
"y) coordinate. ''' x: int y: int def points_between(start: Point, end: Point) ->",
"5, part 2 ''' vents = parse_input(lines) vent_points: Counter = Counter() for (start,",
"sign(end.y - start.y) x = start.x y = start.y while x != end.x",
"p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): '''",
"Point: ''' Represents a single (x, y) coordinate. ''' x: int y: int",
">= 2) @dataclass(frozen=True) class Point: ''' Represents a single (x, y) coordinate. '''",
"Parses the problem input and returns a list of (Point, Point) tuples describing",
"end) in vents: if start.x == end.x or start.y == end.y: vent_points.update(points_between(start, end))",
"Point(x, y) def sign(value: int) -> int: ''' Returns the sign of value,",
"int: ''' Solver for Day 5, part 2 ''' vents = parse_input(lines) vent_points:",
"= [] for line in lines: start, _, end = line.split() p1_x, p1_y",
"-> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 ->",
"python ''' Solvers and example test cases for Day 5 of the Advent",
"unittest def part1(lines: Iterable[str]) -> int: ''' Solver for Day 5, part 1",
"value is negative, or 0 if value is zero. ''' if value <",
"test cases for Day 5, as specified in the problem description ''' #",
"of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter from dataclasses",
"return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the problem input",
"count) in vent_points.most_common() if count >= 2) def part2(lines: Iterable[str]) -> int: '''",
"vents = parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents: if",
"count) in vent_points.most_common() if count >= 2) @dataclass(frozen=True) class Point: ''' Represents a",
"part1(lines: Iterable[str]) -> int: ''' Solver for Day 5, part 1 ''' vents",
"-> List[Tuple[Point, Point]]: ''' Parses the problem input and returns a list of",
"2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2']",
"Iterable[Point]: ''' Iterates over the integral points between start and end (inclusive). Line",
"Counter = Counter() for (start, end) in vents: if start.x == end.x or",
"sign(value: int) -> int: ''' Returns the sign of value, i.e. 1 if",
"vent_points: Counter = Counter() for (start, end) in vents: if start.x == end.x",
"Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the problem input and returns a list",
"''' Solver for Day 5, part 1 ''' vents = parse_input(lines) vent_points: Counter",
"Represents a single (x, y) coordinate. ''' x: int y: int def points_between(start:",
"problem input and returns a list of (Point, Point) tuples describing the vents.",
"2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4',",
"''' Solver for Day 5, part 2 ''' vents = parse_input(lines) vent_points: Counter",
"vents class TestDay05(unittest.TestCase): ''' Example test cases for Day 5, as specified in",
"start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase):",
"for (start, end) in vents: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in",
"-> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def test_part1_example(self):",
"must be either vertical, horizontal, or 45 degrees. ''' x_step = sign(end.x -",
"a single (x, y) coordinate. ''' x: int y: int def points_between(start: Point,",
"import dataclass from typing import Iterable, List, Tuple import unittest def part1(lines: Iterable[str])",
"horizontal, or 45 degrees. ''' x_step = sign(end.x - start.x) y_step = sign(end.y",
"and example test cases for Day 5 of the Advent of Code 2021.",
"is negative, or 0 if value is zero. ''' if value < 0:",
"= [ '0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 ->",
"and end (inclusive). Line must be either vertical, horizontal, or 45 degrees. '''",
"< 0: return -1 if value == 0: return 0 return 1 def",
"collections import Counter from dataclasses import dataclass from typing import Iterable, List, Tuple",
"in vent_points.most_common() if count >= 2) def part2(lines: Iterable[str]) -> int: ''' Solver",
"dataclasses import dataclass from typing import Iterable, List, Tuple import unittest def part1(lines:",
"part 1 ''' vents = parse_input(lines) vent_points: Counter = Counter() for (start, end)",
"in vent_points.most_common() if count >= 2) @dataclass(frozen=True) class Point: ''' Represents a single",
"= Counter() for (start, end) in vents: if start.x == end.x or start.y",
"Day 5, part 2 ''' vents = parse_input(lines) vent_points: Counter = Counter() for",
"the problem description ''' # pylint: disable=missing-function-docstring def setUp(self): self.data = [ '0,9",
"-> 8,8', '5,5 -> 8,2'] def test_part1_example(self): self.assertEqual(part1(self.data), 5) def test_part2_example(self): self.assertEqual(part2(self.data), 12)",
"vents. ''' vents = [] for line in lines: start, _, end =",
"setUp(self): self.data = [ '0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4',",
"end.x or start.y == end.y: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in",
"return -1 if value == 0: return 0 return 1 def parse_input(lines: Iterable[str])",
"int def points_between(start: Point, end: Point) -> Iterable[Point]: ''' Iterates over the integral",
"end.y: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if count >=",
"'0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def",
"int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example test cases for Day",
"5, as specified in the problem description ''' # pylint: disable=missing-function-docstring def setUp(self):",
"-> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 ->",
"value is zero. ''' if value < 0: return -1 if value ==",
"1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def test_part1_example(self): self.assertEqual(part1(self.data), 5) def test_part2_example(self):",
"- start.y) x = start.x y = start.y while x != end.x or",
"from collections import Counter from dataclasses import dataclass from typing import Iterable, List,",
"'6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5",
"x_step = sign(end.x - start.x) y_step = sign(end.y - start.y) x = start.x",
"end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example test cases",
"input and returns a list of (Point, Point) tuples describing the vents. '''",
"if value is positive, -1 if value is negative, or 0 if value",
"= start.x y = start.y while x != end.x or y != end.y:",
"points between start and end (inclusive). Line must be either vertical, horizontal, or",
"value < 0: return -1 if value == 0: return 0 return 1",
"or 0 if value is zero. ''' if value < 0: return -1",
"description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter from dataclasses import dataclass from typing",
"y += y_step yield Point(x, y) def sign(value: int) -> int: ''' Returns",
"Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example test cases for Day 5,",
"is zero. ''' if value < 0: return -1 if value == 0:",
"zero. ''' if value < 0: return -1 if value == 0: return",
"the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter",
"or start.y == end.y: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common()",
"Returns the sign of value, i.e. 1 if value is positive, -1 if",
"(inclusive). Line must be either vertical, horizontal, or 45 degrees. ''' x_step =",
"start.y) x = start.x y = start.y while x != end.x or y",
"disable=missing-function-docstring def setUp(self): self.data = [ '0,9 -> 5,9', '8,0 -> 0,8', '9,4",
"Counter() for (start, end) in vents: vent_points.update(points_between(start, end)) return sum(1 for (_, count)",
"Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter from",
"(_, count) in vent_points.most_common() if count >= 2) def part2(lines: Iterable[str]) -> int:",
"sign of value, i.e. 1 if value is positive, -1 if value is",
"for Day 5 of the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> '''",
"a list of (Point, Point) tuples describing the vents. ''' vents = []",
"0 if value is zero. ''' if value < 0: return -1 if",
"2) @dataclass(frozen=True) class Point: ''' Represents a single (x, y) coordinate. ''' x:",
"Iterates over the integral points between start and end (inclusive). Line must be",
"end)) return sum(1 for (_, count) in vent_points.most_common() if count >= 2) def",
"returns a list of (Point, Point) tuples describing the vents. ''' vents =",
"value is positive, -1 if value is negative, or 0 if value is",
"Counter from dataclasses import dataclass from typing import Iterable, List, Tuple import unittest",
"= line.split() p1_x, p1_y = start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x),",
"i.e. 1 if value is positive, -1 if value is negative, or 0",
"points_between(start: Point, end: Point) -> Iterable[Point]: ''' Iterates over the integral points between",
"p1_y = start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents",
"list of (Point, Point) tuples describing the vents. ''' vents = [] for",
"end)) return sum(1 for (_, count) in vent_points.most_common() if count >= 2) @dataclass(frozen=True)",
"@dataclass(frozen=True) class Point: ''' Represents a single (x, y) coordinate. ''' x: int",
"Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import Counter from dataclasses import",
"(_, count) in vent_points.most_common() if count >= 2) @dataclass(frozen=True) class Point: ''' Represents",
"(start, end) in vents: if start.x == end.x or start.y == end.y: vent_points.update(points_between(start,",
"if value < 0: return -1 if value == 0: return 0 return",
"problem description ''' # pylint: disable=missing-function-docstring def setUp(self): self.data = [ '0,9 ->",
"''' x_step = sign(end.x - start.x) y_step = sign(end.y - start.y) x =",
"5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4',",
"if value is zero. ''' if value < 0: return -1 if value",
"[] for line in lines: start, _, end = line.split() p1_x, p1_y =",
"= start.y while x != end.x or y != end.y: yield Point(x, y)",
"''' Example test cases for Day 5, as specified in the problem description",
"int: ''' Returns the sign of value, i.e. 1 if value is positive,",
"int: ''' Solver for Day 5, part 1 ''' vents = parse_input(lines) vent_points:",
"(x, y) coordinate. ''' x: int y: int def points_between(start: Point, end: Point)",
"or 45 degrees. ''' x_step = sign(end.x - start.x) y_step = sign(end.y -",
"3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9',",
"= sign(end.y - start.y) x = start.x y = start.y while x !=",
"''' from collections import Counter from dataclasses import dataclass from typing import Iterable,",
"vertical, horizontal, or 45 degrees. ''' x_step = sign(end.x - start.x) y_step =",
"the problem input and returns a list of (Point, Point) tuples describing the",
"vent_points.most_common() if count >= 2) @dataclass(frozen=True) class Point: ''' Represents a single (x,",
"of the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from collections import",
"y = start.y while x != end.x or y != end.y: yield Point(x,",
"the integral points between start and end (inclusive). Line must be either vertical,",
"self.data = [ '0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2",
"Day 5 of the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/5> ''' from",
"x: int y: int def points_between(start: Point, end: Point) -> Iterable[Point]: ''' Iterates",
"1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the problem input and",
"def part1(lines: Iterable[str]) -> int: ''' Solver for Day 5, part 1 '''",
"'2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4",
"in vents: if start.x == end.x or start.y == end.y: vent_points.update(points_between(start, end)) return",
"cases for Day 5, as specified in the problem description ''' # pylint:",
"vent_points.most_common() if count >= 2) def part2(lines: Iterable[str]) -> int: ''' Solver for",
"Point, end: Point) -> Iterable[Point]: ''' Iterates over the integral points between start",
"-> Iterable[Point]: ''' Iterates over the integral points between start and end (inclusive).",
"== end.x or start.y == end.y: vent_points.update(points_between(start, end)) return sum(1 for (_, count)",
"in the problem description ''' # pylint: disable=missing-function-docstring def setUp(self): self.data = [",
"Iterable, List, Tuple import unittest def part1(lines: Iterable[str]) -> int: ''' Solver for",
"''' Iterates over the integral points between start and end (inclusive). Line must",
"def sign(value: int) -> int: ''' Returns the sign of value, i.e. 1",
"Iterable[str]) -> int: ''' Solver for Day 5, part 2 ''' vents =",
"line.split() p1_x, p1_y = start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y))))",
"= end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class TestDay05(unittest.TestCase): ''' Example test",
"TestDay05(unittest.TestCase): ''' Example test cases for Day 5, as specified in the problem",
"for (_, count) in vent_points.most_common() if count >= 2) def part2(lines: Iterable[str]) ->",
"pylint: disable=missing-function-docstring def setUp(self): self.data = [ '0,9 -> 5,9', '8,0 -> 0,8',",
"over the integral points between start and end (inclusive). Line must be either",
"+= x_step y += y_step yield Point(x, y) def sign(value: int) -> int:",
"''' Returns the sign of value, i.e. 1 if value is positive, -1",
"while x != end.x or y != end.y: yield Point(x, y) x +=",
"of (Point, Point) tuples describing the vents. ''' vents = [] for line",
"!= end.y: yield Point(x, y) x += x_step y += y_step yield Point(x,",
"'0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0",
"yield Point(x, y) x += x_step y += y_step yield Point(x, y) def",
"x += x_step y += y_step yield Point(x, y) def sign(value: int) ->",
"start.y while x != end.x or y != end.y: yield Point(x, y) x",
"''' vents = parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents:",
"part 2 ''' vents = parse_input(lines) vent_points: Counter = Counter() for (start, end)",
"!= end.x or y != end.y: yield Point(x, y) x += x_step y",
"y: int def points_between(start: Point, end: Point) -> Iterable[Point]: ''' Iterates over the",
"#! /usr/bin/env python ''' Solvers and example test cases for Day 5 of",
"'7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0",
"if count >= 2) def part2(lines: Iterable[str]) -> int: ''' Solver for Day",
"0 return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the problem",
"in vents: vent_points.update(points_between(start, end)) return sum(1 for (_, count) in vent_points.most_common() if count",
"Solvers and example test cases for Day 5 of the Advent of Code",
"(Point, Point) tuples describing the vents. ''' vents = [] for line in",
"between start and end (inclusive). Line must be either vertical, horizontal, or 45",
"int) -> int: ''' Returns the sign of value, i.e. 1 if value",
"Point]]: ''' Parses the problem input and returns a list of (Point, Point)",
"the sign of value, i.e. 1 if value is positive, -1 if value",
"end.x or y != end.y: yield Point(x, y) x += x_step y +=",
"parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the problem input and returns a",
"List, Tuple import unittest def part1(lines: Iterable[str]) -> int: ''' Solver for Day",
"start.x == end.x or start.y == end.y: vent_points.update(points_between(start, end)) return sum(1 for (_,",
"import Iterable, List, Tuple import unittest def part1(lines: Iterable[str]) -> int: ''' Solver",
"-1 if value == 0: return 0 return 1 def parse_input(lines: Iterable[str]) ->",
"''' # pylint: disable=missing-function-docstring def setUp(self): self.data = [ '0,9 -> 5,9', '8,0",
"'8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4",
"from dataclasses import dataclass from typing import Iterable, List, Tuple import unittest def",
"if value == 0: return 0 return 1 def parse_input(lines: Iterable[str]) -> List[Tuple[Point,",
"y_step yield Point(x, y) def sign(value: int) -> int: ''' Returns the sign",
"value, i.e. 1 if value is positive, -1 if value is negative, or",
"is positive, -1 if value is negative, or 0 if value is zero.",
"positive, -1 if value is negative, or 0 if value is zero. '''",
"start.x) y_step = sign(end.y - start.y) x = start.x y = start.y while",
"degrees. ''' x_step = sign(end.x - start.x) y_step = sign(end.y - start.y) x",
"= start.split(',') p2_x, p2_y = end.split(',') vents.append((Point(int(p1_x), int(p1_y)), Point(int(p2_x), int(p2_y)))) return vents class",
"of value, i.e. 1 if value is positive, -1 if value is negative,",
"x_step y += y_step yield Point(x, y) def sign(value: int) -> int: '''",
"+= y_step yield Point(x, y) def sign(value: int) -> int: ''' Returns the",
"5, part 1 ''' vents = parse_input(lines) vent_points: Counter = Counter() for (start,",
"= parse_input(lines) vent_points: Counter = Counter() for (start, end) in vents: vent_points.update(points_between(start, end))",
"import unittest def part1(lines: Iterable[str]) -> int: ''' Solver for Day 5, part",
"or y != end.y: yield Point(x, y) x += x_step y += y_step",
"x != end.x or y != end.y: yield Point(x, y) x += x_step",
"def parse_input(lines: Iterable[str]) -> List[Tuple[Point, Point]]: ''' Parses the problem input and returns",
"45 degrees. ''' x_step = sign(end.x - start.x) y_step = sign(end.y - start.y)"
] |
[
"sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma vector evaluator",
"ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue)",
"np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:]",
"If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it tried to look",
"/ (difference btw the diagonal and the current eigenvalue) ''' ref = create_matrix()",
"create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v",
"= sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref)",
"= matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def",
"np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test that if",
"Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref",
"= create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec =",
"<= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma vector evaluator and",
"test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma vector evaluator and preconditioner sve =",
"and fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result",
"= initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref)",
"sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref)",
"ref = create_matrix() diag = initialize_diagonalizer(ref) # Set python specific sigma vector evaluator",
"method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result",
"j): return def create_matrix(): # create a selfadjoint matrix matrix = np.random.rand(100,100) matrix",
"Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) #",
"a vector of ones, you just get -1.0 / (difference btw the diagonal",
"Create and fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec)",
"btw the diagonal and the current eigenvalue) ''' ref = create_matrix() diag =",
"Get reference numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5)",
"def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref) # Set python specific sigma",
"prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100)",
"= create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 *",
"numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix =",
"-1.0 / (difference btw the diagonal and the current eigenvalue) ''' ref =",
"= initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent())",
"initialize_diagonalizer(matrix): # Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec =",
"create_matrix(): # create a selfadjoint matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix +",
"Laboratory of Physical Chemistry, Reiher Group. See LICENSE.txt for details. \"\"\" import pytest",
"under the 3-clause BSD license. Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher",
"for the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator =",
"= SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) # Get reference numbers w,",
"vector evaluator # Note: first initialize, then assign to prevent auto casting. #",
"ones, you just get -1.0 / (difference btw the diagonal and the current",
"def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors)",
"ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec",
"python specific sigma vector evaluator # Note: first initialize, then assign to prevent",
"np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix):",
"for details. \"\"\" import pytest import scine_utilities as scine import numpy as np",
"# If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it tried to",
"look for the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator",
"LICENSE.txt for details. \"\"\" import pytest import scine_utilities as scine import numpy as",
"specific sigma vector evaluator # Note: first initialize, then assign to prevent auto",
"and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non",
"prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag",
"test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref) result",
"return def swap(self, i, j): return def create_matrix(): # create a selfadjoint matrix",
"test_Preconditioner(): ''' Test that if you try to precondition a vector of ones,",
"(difference btw the diagonal and the current eigenvalue) ''' ref = create_matrix() diag",
"Group. See LICENSE.txt for details. \"\"\" import pytest import scine_utilities as scine import",
"+ np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix): # Create sigma vector",
"assign to prevent auto casting. # If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) #",
"and the current eigenvalue) ''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector =",
"# Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)])",
"diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v =",
"matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix): # Create sigma vector evaluator and",
"= SigmaVectorEvaluatorPython(ref) # then it it tried to look for the method SigmaVectorEvaluator::evaluate()",
"result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner():",
"numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson():",
"prevent auto casting. # If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it",
"assert np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix())",
"# Set python specific sigma vector evaluator # Note: first initialize, then assign",
"i, j): return def create_matrix(): # create a selfadjoint matrix matrix = np.random.rand(100,100)",
"return diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0",
"def test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100))",
"class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors): return",
"* np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test that",
"1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma vector evaluator and preconditioner",
"diagonal and the current eigenvalue) ''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector",
"to precondition a vector of ones, you just get -1.0 / (difference btw",
"= scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal Davidson diag",
"def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get",
"diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 *",
"to prevent auto casting. # If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then",
"diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference",
"1 return matrix def initialize_diagonalizer(matrix): # Create sigma vector evaluator and preconditioner sve",
"Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator():",
"w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref",
"def initialize_diagonalizer(matrix): # Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec",
"vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and",
"and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non",
"auto casting. # If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it",
"= initialize_diagonalizer(ref) # Set python specific sigma vector evaluator # Note: first initialize,",
"ref = create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference numbers",
"write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it tried to look for the",
"assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag =",
"= sve result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref)",
"ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. See LICENSE.txt for details. \"\"\"",
"w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref",
"the 3-clause BSD license. Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.",
"preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal",
"evaluator # Note: first initialize, then assign to prevent auto casting. # If",
"= scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator",
"matrix def initialize_diagonalizer(matrix): # Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix)",
"is licensed under the 3-clause BSD license. Copyright ETH Zurich, Laboratory of Physical",
"(diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix()",
"prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100)",
"scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:]) def",
"the diagonal and the current eigenvalue) ''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)]",
"create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:]",
"diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result",
"Create and fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec)",
"to look for the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref)",
"scine_utilities as scine import numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self,",
"evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self, i, j):",
"a selfadjoint matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] +=",
"diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref =",
"assert np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test that if you",
"create a selfadjoint matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)]",
"pytest import scine_utilities as scine import numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator):",
"np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix): # Create sigma vector evaluator",
"self.matrix = matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return",
"# Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)])",
"__copyright__ = \"\"\"This code is licensed under the 3-clause BSD license. Copyright ETH",
"SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v",
"ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0",
"def collapsed(self, newSubspaceDimension): return def swap(self, i, j): return def create_matrix(): # create",
"matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self,",
"Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent())",
"as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix",
"details. \"\"\" import pytest import scine_utilities as scine import numpy as np import",
"- sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma vector",
"import scine_utilities as scine import numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def",
"diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref) assert",
"= np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix()",
"3-clause BSD license. Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. See",
"sve result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref) assert",
"np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self, i, j): return def create_matrix():",
"create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag)",
"ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector,",
"__init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def",
"-1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref",
"create_matrix() diag = initialize_diagonalizer(ref) # Set python specific sigma vector evaluator # Note:",
"# Create and fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve",
"then assign to prevent auto casting. # If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref)",
"matrix = np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix",
"selfadjoint matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1",
"# instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent())",
"# Note: first initialize, then assign to prevent auto casting. # If I",
"def create_matrix(): # create a selfadjoint matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix",
"that if you try to precondition a vector of ones, you just get",
"# then it it tried to look for the method SigmaVectorEvaluator::evaluate() # instead",
"= create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w,",
"result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:]",
"then it it tried to look for the method SigmaVectorEvaluator::evaluate() # instead of",
"sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal Davidson",
"= sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner(): '''",
"ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test that if you try to precondition",
"SigmaVectorEvaluatorPython(ref) # then it it tried to look for the method SigmaVectorEvaluator::evaluate() #",
"import pytest import scine_utilities as scine import numpy as np import os class",
"Note: first initialize, then assign to prevent auto casting. # If I write",
"Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. See LICENSE.txt for details.",
"you just get -1.0 / (difference btw the diagonal and the current eigenvalue)",
"np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def",
"diag = initialize_diagonalizer(ref) # Set python specific sigma vector evaluator # Note: first",
"arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag =",
"- sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref) #",
"casting. # If I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it tried",
"= prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer():",
"fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag",
"diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v =",
"just get -1.0 / (difference btw the diagonal and the current eigenvalue) '''",
"- arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag",
"sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) # Get reference numbers",
"test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference",
"you try to precondition a vector of ones, you just get -1.0 /",
"= sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v =",
"Test that if you try to precondition a vector of ones, you just",
"the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve",
"= scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref = create_matrix()",
"<= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref) # Set python",
"scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal Davidson diag =",
"fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result =",
"return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self, i, j): return def",
"= scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference numbers",
"diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5]",
"swap(self, i, j): return def create_matrix(): # create a selfadjoint matrix matrix =",
"diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref) result =",
"def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self, i,",
"scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension):",
"''' Test that if you try to precondition a vector of ones, you",
"of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) # Get",
"diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v",
"= np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def",
"it it tried to look for the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate()",
"SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result =",
"result[:,:]) def test_Preconditioner(): ''' Test that if you try to precondition a vector",
"BSD license. Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. See LICENSE.txt",
"collapsed(self, newSubspaceDimension): return def swap(self, i, j): return def create_matrix(): # create a",
"= scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator",
"scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator =",
"3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 /",
"SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) # Get reference",
"matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self,",
"scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal Davidson diag =",
"matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix): #",
"evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill",
"= np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix()",
"numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator():",
"diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result =",
"sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create",
"Chemistry, Reiher Group. See LICENSE.txt for details. \"\"\" import pytest import scine_utilities as",
"Reiher Group. See LICENSE.txt for details. \"\"\" import pytest import scine_utilities as scine",
"initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) #",
"Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) #",
"I write diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it tried to look for",
"np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() #",
"reference numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def",
"of Physical Chemistry, Reiher Group. See LICENSE.txt for details. \"\"\" import pytest import",
"create_matrix() # Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec =",
"SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors): return np.dot(self.matrix,",
"Zurich, Laboratory of Physical Chemistry, Reiher Group. See LICENSE.txt for details. \"\"\" import",
"np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag",
"Set python specific sigma vector evaluator # Note: first initialize, then assign to",
"instead of SigmaVectorEvaluatorPython::evaluate() sve = SigmaVectorEvaluatorPython(ref) diag.sigma_vector_evaluator = sve result = diag.solve(scine.core.Log.silent()) #",
"import numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix",
"\"\"\"This code is licensed under the 3-clause BSD license. Copyright ETH Zurich, Laboratory",
"* ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test that if you try to",
"scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve",
"== result[:,:]) def test_Preconditioner(): ''' Test that if you try to precondition a",
"sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create",
"license. Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. See LICENSE.txt for",
"it tried to look for the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve",
"diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve =",
"sigma vector evaluator # Note: first initialize, then assign to prevent auto casting.",
"try to precondition a vector of ones, you just get -1.0 / (difference",
"vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and",
"test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref) # Set python specific sigma vector",
"diag.sigma_vector_evaluator = SigmaVectorEvaluatorPython(ref) # then it it tried to look for the method",
"1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref) # Set python specific",
"of ones, you just get -1.0 / (difference btw the diagonal and the",
"initialize_diagonalizer(ref) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref) assert",
"return matrix def initialize_diagonalizer(matrix): # Create sigma vector evaluator and preconditioner sve =",
"os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self, guess_vectors):",
"def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag = initialize_diagonalizer(ref)",
"v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref =",
"Physical Chemistry, Reiher Group. See LICENSE.txt for details. \"\"\" import pytest import scine_utilities",
"sve diag.set_preconditioner(prec) return diag def test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result",
"np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma",
"initialize_diagonalizer(ref) # Set python specific sigma vector evaluator # Note: first initialize, then",
"# Get reference numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <=",
"test_SigmaVectorEvaluator(): ref = create_matrix() sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert",
"= create_matrix() diag = initialize_diagonalizer(ref) # Set python specific sigma vector evaluator #",
"return def create_matrix(): # create a selfadjoint matrix matrix = np.random.rand(100,100) matrix =",
"= scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag -",
"arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] ==",
"sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test",
"= scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:] == result[:,:])",
"Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return diag def",
"arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref = create_matrix() diag =",
"v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref =",
"tried to look for the method SigmaVectorEvaluator::evaluate() # instead of SigmaVectorEvaluatorPython::evaluate() sve =",
"# create a selfadjoint matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix))",
"= 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix): # Create",
"Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get",
"prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag",
"np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref)",
"precondition a vector of ones, you just get -1.0 / (difference btw the",
"licensed under the 3-clause BSD license. Copyright ETH Zurich, Laboratory of Physical Chemistry,",
"= create_matrix() # Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec",
"== -1.0 / (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson():",
"current eigenvalue) ''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue",
"guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self, i, j): return def create_matrix(): #",
"first initialize, then assign to prevent auto casting. # If I write diag.sigma_vector_evaluator",
"sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal Davidson",
"if you try to precondition a vector of ones, you just get -1.0",
"import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def evaluate(self,",
"def test_Preconditioner(): ''' Test that if you try to precondition a vector of",
"See LICENSE.txt for details. \"\"\" import pytest import scine_utilities as scine import numpy",
"= np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert",
"initialize, then assign to prevent auto casting. # If I write diag.sigma_vector_evaluator =",
"scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) # Create and fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator =",
"= \"\"\"This code is licensed under the 3-clause BSD license. Copyright ETH Zurich,",
"ref = create_matrix() # Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref)",
"sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithPythonSigmaVectorEvaluator(): ref = create_matrix() diag = initialize_diagonalizer(ref) # Set",
"scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue))",
"assert np.all(result.eigenvalues[:] - sorted(w)[:5] <= 1.0e-5) def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create",
"newSubspaceDimension): return def swap(self, i, j): return def create_matrix(): # create a selfadjoint",
"# Create and fill Non Orthogonal Davidson diag = scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve",
"matrix matrix = np.random.rand(100,100) matrix = 0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return",
"and fill Non Orthogonal Davidson diag = scine.NonOrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) return",
"Create sigma vector evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(ref) prec = scine.IndirectPreconditionerEvaluator(ref[np.diag_indices_from(ref)]) #",
"vector of ones, you just get -1.0 / (difference btw the diagonal and",
"scine import numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self)",
"def test_DiagonalizeWithOrthogonalDavidson(): ref = create_matrix() # Create sigma vector evaluator and preconditioner sve",
"def swap(self, i, j): return def create_matrix(): # create a selfadjoint matrix matrix",
"0.5*(matrix + np.transpose(matrix)) matrix[np.diag_indices_from(matrix)] += 1 return matrix def initialize_diagonalizer(matrix): # Create sigma",
"as scine import numpy as np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix):",
"np import os class SigmaVectorEvaluatorPython(scine.SigmaVectorEvaluator): def __init__(self, matrix): scine.SigmaVectorEvaluator.__init__(self) self.matrix = matrix def",
"''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5",
"get -1.0 / (difference btw the diagonal and the current eigenvalue) ''' ref",
"result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0 / (diag - arbitrary_eigenvalue)) def",
"/ (diag - arbitrary_eigenvalue)) def test_InitializeDiagonalizer(): diag = initialize_diagonalizer(create_matrix()) def test_DiagonalizeWithNonOrthogonalDavidson(): ref =",
"the current eigenvalue) ''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100)",
"= 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result = prec.evaluate(ones_vector, arbitrary_eigenvalue) assert np.all(result[:] == -1.0",
"code is licensed under the 3-clause BSD license. Copyright ETH Zurich, Laboratory of",
"np.all(2.0 * ref[:,:] == result[:,:]) def test_Preconditioner(): ''' Test that if you try",
"evaluator and preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill",
"+= 1 return matrix def initialize_diagonalizer(matrix): # Create sigma vector evaluator and preconditioner",
"= diag.solve(scine.core.Log.silent()) # Get reference numbers w, v = np.linalg.eig(ref) assert np.all(result.eigenvalues[:] -",
"preconditioner sve = scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal",
"scine.OrthogonalDavidson(5,100) diag.sigma_vector_evaluator = sve diag.set_preconditioner(prec) result = diag.solve(scine.core.Log.silent()) # Get reference numbers w,",
"= ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue = 3.5 prec = scine.IndirectPreconditionerEvaluator(diag) result =",
"guess_vectors): return np.dot(self.matrix, guess_vectors) def collapsed(self, newSubspaceDimension): return def swap(self, i, j): return",
"= scine.IndirectSigmaVectorEvaluator(matrix) prec = scine.IndirectPreconditionerEvaluator(matrix[np.diag_indices_from(matrix)]) # Create and fill Non Orthogonal Davidson diag",
"sve = scine.IndirectSigmaVectorEvaluator(ref) result = sve.evaluate(2.0 * np.identity(100)) assert np.all(2.0 * ref[:,:] ==",
"eigenvalue) ''' ref = create_matrix() diag = ref[np.diag_indices_from(ref)] ones_vector = np.ones(100) arbitrary_eigenvalue =",
"\"\"\" import pytest import scine_utilities as scine import numpy as np import os"
] |
[
"[128, 128, 512]) out = identity_block(out, [128, 128, 512]) out = conv_block(out, [256,",
"= BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out",
"= nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out =",
"Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization",
"out = BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out =",
"mode='sum') out = layers.add([out, shortcut]) out = Activation('relu')(out) return out def buildNet(): inp",
"import BatchNormalization from keras.models import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'",
"shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out,",
"= BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out =",
"import Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import",
"Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out)",
"224, 3)) out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out)",
"Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3): k1,",
"os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut",
"= Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out = Conv2D(k2,",
"BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum') out = layers.add([out, shortcut]) out =",
"out = identity_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256]) out",
"2048]) out = identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4, 4))(out) out =",
"out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out",
"k1, k2, k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x)",
"keras import layers from keras.layers import Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D,",
"plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter",
"'2' def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x",
"3)) out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out",
"[64, 64, 256]) out = identity_block(out, [64, 64, 256]) out = conv_block(out, [128,",
"from keras.layers import Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from",
"[128, 128, 512]) out = conv_block(out, [256, 256, 1024]) out = identity_block(out, [256,",
"padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out)",
"out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out",
"shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3):",
"= BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out)",
"= '2' def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut =",
"keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential",
"k2, k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out",
"512, 2048]) out = identity_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512,",
"Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model",
"= Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut],",
"= identity_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out =",
"256, 1024]) out = identity_block(out, [256, 256, 1024]) out = conv_block(out, [512, 512,",
"128, 512]) out = conv_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256,",
"= identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4, 4))(out) out = Flatten()(out) #",
"model if __name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3])",
"= Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7),",
"nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x out = Conv2D(k1,",
"out = BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out =",
"k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out =",
"Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out",
"out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut",
"展平 out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model if __name__",
"'__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3])",
"conv_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out = identity_block(out,",
"2048]) out = AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平 out = Dense(1000,",
"ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net = buildNet() net.compile(optimizer='adam',loss='categorical_crossentropy',",
"out = Activation('relu')(out) return out def buildNet(): inp = Input(shape=(224, 224, 3)) out",
"out = identity_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out",
"buildNet(): inp = Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64,",
"Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum') out=",
"out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model if __name__ ==",
"3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64, 64, 256]) out = identity_block(out,",
"merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense,",
"ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization from keras.models",
"out def buildNet(): inp = Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp) out",
"identity_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out = conv_block(out,",
"out = conv_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256]) out",
"# 展平 out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model if",
"64, 256]) out = identity_block(out, [64, 64, 256]) out = identity_block(out, [64, 64,",
"BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return",
"= ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 =",
"out = conv_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out",
"padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out",
"strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut =",
"out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1),",
"out = conv_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out",
"= identity_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256]) out =",
"out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out = merge([out, shortcut],",
"Activation('relu')(out) return out def buildNet(): inp = Input(shape=(224, 224, 3)) out = ZeroPadding2D((3,",
"= BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut =",
"out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1),",
"return model if __name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 =",
"def buildNet(): inp = Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp) out =",
"out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return out def",
"strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out)",
"__name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50",
"= ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net = buildNet() net.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy']) plot_model(net, to_file='./models/resnet.png')",
"resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152",
"padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum') out = layers.add([out,",
"keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3",
"[64, 64, 256]) out = identity_block(out, [64, 64, 256]) out = identity_block(out, [64,",
"[512, 512, 2048]) out = AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平 out",
"[256, 256, 1024]) out = conv_block(out, [512, 512, 2048]) out = identity_block(out, [512,",
"layers.add([out,shortcut]) out = Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3",
"out = identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4, 4))(out) out = Flatten()(out)",
"Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2,",
"padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut)",
"= x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2,",
"return out def buildNet(): inp = Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp)",
"= out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3,",
"= ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out)",
"[64, 64, 256]) out = conv_block(out, [128, 128, 512]) out = identity_block(out, [128,",
"256]) out = conv_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512])",
"512]) out = identity_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512])",
"= Activation('relu')(out) return out def buildNet(): inp = Input(shape=(224, 224, 3)) out =",
"kernel_size=3): k1, k2, k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1),",
"strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out",
"BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64, 64,",
"x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3),",
"= BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out =",
"strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out)",
"out= layers.add([out,shortcut]) out = Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3): k1, k2,",
"3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out =",
"ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out",
"padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) #",
"= conv_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out =",
"activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model if __name__ == '__main__': # resNet18",
"shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out =",
"outputs=out) return model if __name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34",
"= Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter",
"AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out) model =",
"Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut)",
"= Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out)",
"= layers.add([out, shortcut]) out = Activation('relu')(out) return out def buildNet(): inp = Input(shape=(224,",
"BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out =",
"= Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum')",
"shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out",
"strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum') out =",
"from keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL']",
"out def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x",
"1024]) out = identity_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024])",
"= x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out =",
"BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3,",
"keras.layers import Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core",
"= AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out) model",
"Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2,",
"512]) out = identity_block(out, [128, 128, 512]) out = conv_block(out, [256, 256, 1024])",
"= conv_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out =",
"= ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 =",
"out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3,",
"out = identity_block(out, [64, 64, 256]) out = conv_block(out, [128, 128, 512]) out",
"resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net = buildNet() net.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy']) plot_model(net,",
"out = merge([out, shortcut], mode='sum') out = layers.add([out, shortcut]) out = Activation('relu')(out) return",
"kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut])",
"layers from keras.layers import Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D)",
"out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out =",
"4))(out) out = Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp,",
"# resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net",
"128, 512]) out = identity_block(out, [128, 128, 512]) out = conv_block(out, [256, 256,",
"[256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out = identity_block(out, [256,",
"out = Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 =",
"mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3): k1,",
"from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3): k1, k2,",
"out = identity_block(out, [256, 256, 1024]) out = conv_block(out, [512, 512, 2048]) out",
"BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out",
"strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out =",
"ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net = buildNet() net.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy']) plot_model(net, to_file='./models/resnet.png') net.summary()",
"[512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out = identity_block(out, [512,",
"kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out =",
"= Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model if __name__ == '__main__':",
"out = conv_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out",
"[512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4, 4))(out)",
"= nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out)",
"kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out =",
"shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum') out = layers.add([out, shortcut])",
"= identity_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out =",
"identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x out =",
"Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size),",
"from keras.models import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x,",
"k1, k2, k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2),",
"Dense, Flatten from keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential from keras.utils import",
"out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1),",
"from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten",
"from keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization from keras.models import",
"import Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential from",
"out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1),",
"= conv_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256]) out =",
"= BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum') out = layers.add([out, shortcut]) out",
"Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation,",
"keras.models import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter,",
"2), padding=\"same\")(out) out = conv_block(out, [64, 64, 256]) out = identity_block(out, [64, 64,",
"out = layers.add([out, shortcut]) out = Activation('relu')(out) return out def buildNet(): inp =",
"strides=(1,1), padding='same',activation=\"relu\")(out) out = BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out)",
"out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out =",
"= BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out)",
"= MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64, 64, 256]) out",
"conv_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256]) out = identity_block(out,",
"512, 2048]) out = AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平 out =",
"= Model(inputs=inp, outputs=out) return model if __name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2])",
"x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out",
"k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out",
"# out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return out",
"kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum') out",
"Model(inputs=inp, outputs=out) return model if __name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) #",
"= identity_block(out, [256, 256, 1024]) out = conv_block(out, [512, 512, 2048]) out =",
"Flatten from keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential from keras.utils import plot_model",
"= Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out)",
"= identity_block(out, [64, 64, 256]) out = conv_block(out, [128, 128, 512]) out =",
"conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x out =",
"ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3])",
"# resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) #",
"Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = Conv2D(k2, kernel_size=(3,3), strides=(1,1), padding='same',activation=\"relu\")(out) out",
"k2, k3 = nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x)",
"out = identity_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out",
"model = Model(inputs=inp, outputs=out) return model if __name__ == '__main__': # resNet18 =",
"# resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net = buildNet() net.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy'])",
"out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64, 64, 256])",
"out = Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out)",
"= merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return out def conv_block(x,",
"shortcut], mode='sum') out = layers.add([out, shortcut]) out = Activation('relu')(out) return out def buildNet():",
"inp = Input(shape=(224, 224, 3)) out = ZeroPadding2D((3, 3))(inp) out = Conv2D(64, kernel_size=(7,",
"= identity_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out =",
"strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out = merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out",
"Activation('relu')(out) return out def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut",
"kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2),",
"[128, 128, 512]) out = identity_block(out, [128, 128, 512]) out = identity_block(out, [128,",
"2048]) out = identity_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048])",
"resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101",
"kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out = Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1),",
"out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out,",
"128, 512]) out = identity_block(out, [128, 128, 512]) out = identity_block(out, [128, 128,",
"if __name__ == '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) #",
"nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out",
"identity_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out = identity_block(out,",
"shortcut]) out = Activation('relu')(out) return out def buildNet(): inp = Input(shape=(224, 224, 3))",
"merge([out, shortcut], mode='sum') out = layers.add([out, shortcut]) out = Activation('relu')(out) return out def",
"(AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization import",
"MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization from",
"256, 1024]) out = identity_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256,",
"keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten from",
"import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3):",
"merge([out, shortcut], mode='sum') out= layers.add([out,shortcut]) out = Activation('relu')(out) return out def conv_block(x, nb_filter,",
"[256, 256, 1024]) out = identity_block(out, [256, 256, 1024]) out = conv_block(out, [512,",
"= identity_block(out, [128, 128, 512]) out = conv_block(out, [256, 256, 1024]) out =",
"identity_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4,",
"= merge([out, shortcut], mode='sum') out = layers.add([out, shortcut]) out = Activation('relu')(out) return out",
"7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out)",
"512, 2048]) out = identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4, 4))(out) out",
"out = identity_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out",
"256]) out = identity_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256])",
"import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 =",
"identity_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out = conv_block(out,",
"os from keras import layers from keras.layers import Input, merge from keras.layers.convolutional import",
"layers.add([out, shortcut]) out = Activation('relu')(out) return out def buildNet(): inp = Input(shape=(224, 224,",
"import os from keras import layers from keras.layers import Input, merge from keras.layers.convolutional",
"= Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2),",
"BatchNormalization from keras.models import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def",
"BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3,",
"conv_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out = identity_block(out,",
"nb_filter shortcut = x out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out)",
"256, 1024]) out = conv_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512,",
"ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3])",
"identity_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out = identity_block(out,",
"256]) out = identity_block(out, [64, 64, 256]) out = conv_block(out, [128, 128, 512])",
"from keras import layers from keras.layers import Input, merge from keras.layers.convolutional import (AveragePooling2D,",
"1024]) out = conv_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048])",
"# resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) #",
"out = Conv2D(k1, kernel_size=(1,1), strides=(2,2), padding=\"valid\",activation=\"relu\")(x) out = BatchNormalization(axis=3)(out) out = out =",
"= ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net = buildNet()",
"kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out",
"identity_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256]) out = conv_block(out,",
"strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64, 64, 256]) out = identity_block(out, [64,",
"identity_block(out, [64, 64, 256]) out = conv_block(out, [128, 128, 512]) out = identity_block(out,",
"import (AveragePooling2D, Conv2D, MaxPooling2D, ZeroPadding2D) from keras.layers.core import Activation, Dense, Flatten from keras.layers.normalization",
"64, 256]) out = conv_block(out, [128, 128, 512]) out = identity_block(out, [128, 128,",
"512]) out = conv_block(out, [256, 256, 1024]) out = identity_block(out, [256, 256, 1024])",
"identity_block(out, [512, 512, 2048]) out = AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平",
"resNet50 = ResNet(block_num=[3,4,6,3]) # resNet101 = ResNet(block_num=[3,4,23,3]) # resNet152 = ResNet(block_num=[3,8,36,3]) net =",
"BatchNormalization(axis=3)(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) # out = merge([out,",
"def identity_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x out",
"= Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return",
"# out = merge([out, shortcut], mode='sum') out = layers.add([out, shortcut]) out = Activation('relu')(out)",
"keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential from keras.utils import plot_model os.environ['TF_CPP_MIN_LOG_LEVEL'] =",
"import layers from keras.layers import Input, merge from keras.layers.convolutional import (AveragePooling2D, Conv2D, MaxPooling2D,",
"conv_block(out, [128, 128, 512]) out = identity_block(out, [128, 128, 512]) out = identity_block(out,",
"Activation, Dense, Flatten from keras.layers.normalization import BatchNormalization from keras.models import Model,Sequential from keras.utils",
"identity_block(out, [128, 128, 512]) out = conv_block(out, [256, 256, 1024]) out = identity_block(out,",
"def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut = x out",
"1024]) out = identity_block(out, [256, 256, 1024]) out = conv_block(out, [512, 512, 2048])",
"= Conv2D(k2, kernel_size=(kernel_size,kernel_size), strides=(1,1), padding=\"same\",activation=\"relu\")(out) out = BatchNormalization()(out) out = Conv2D(k3, kernel_size=(1,1), strides=(1,1),",
"= BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64,",
"padding=\"same\")(out) out = conv_block(out, [64, 64, 256]) out = identity_block(out, [64, 64, 256])",
"out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) #",
"identity_block(out, [256, 256, 1024]) out = conv_block(out, [512, 512, 2048]) out = identity_block(out,",
"= conv_block(out, [512, 512, 2048]) out = identity_block(out, [512, 512, 2048]) out =",
"return out def conv_block(x, nb_filter, kernel_size=3): k1, k2, k3 = nb_filter shortcut =",
"2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out =",
"64, 256]) out = identity_block(out, [64, 64, 256]) out = conv_block(out, [128, 128,",
"out = identity_block(out, [128, 128, 512]) out = conv_block(out, [256, 256, 1024]) out",
"out = AveragePooling2D((4, 4))(out) out = Flatten()(out) # 展平 out = Dense(1000, activation='softmax')(out)",
"Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut = BatchNormalization(axis=3)(shortcut) # out = merge([out, shortcut], mode='sum')",
"kernel_size=(1,1), strides=(1,1), padding=\"valid\")(out) out = BatchNormalization(axis=3)(out) shortcut = Conv2D(k3, kernel_size=(1,1), strides=(2,2), padding=\"valid\")(shortcut) shortcut",
"= Conv2D(64, kernel_size=(7, 7), strides=(2, 2),activation=\"relu\")(out) out = BatchNormalization()(out) out = MaxPooling2D(pool_size=(3, 3),",
"MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(out) out = conv_block(out, [64, 64, 256]) out =",
"== '__main__': # resNet18 = ResNet(block_num=[2,2,2,2]) # resNet34 = ResNet(block_num=[3,4,6,3]) # resNet50 =",
"Dense(1000, activation='softmax')(out) model = Model(inputs=inp, outputs=out) return model if __name__ == '__main__': #"
] |
[
"pyprind n = 100 sleeptime = 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for",
"(80 * '=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80 * '='))",
"Flush\\n') test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys",
"'=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n' %",
"i in range(0, n)] perc = pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i)",
"License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import",
"for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for",
"def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update() if",
"print('%s\\n' % (80 * '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80 *",
"n = 100 sleeptime = 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for i",
"time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime) perc.update()",
"for i in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv' %",
"range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i in range(n):",
"test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update() if __name__",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Force Flush\\n') test_force_flush()",
"PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import pyprind n = 100 sleeptime",
"* '=')) print('%s\\n' % (80 * '=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s'",
"i for i in range(0, n)] perc = pyprind.ProgPercent(len(items)) for i in items:",
"(80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent()",
"def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n,",
"time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv' % i for i in",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Basic Percentage Indicator\\n')",
"(80 * '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n'",
"perc.update() if __name__ == \"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"perc.update() def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc =",
"Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing monitor function\\n') test_monitoring()",
"range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring():",
"monitor=True) for i in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv'",
"i in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv' % i",
"* '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n'",
"test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Item",
"Progress Indicator Utility Author: <NAME> <<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code",
"https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import pyprind n = 100",
"def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime) perc.update() print(perc)",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Item Tracking\\n') test_item_tracking()",
"in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv' % i for",
"print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *",
"perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def",
"i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for i in",
"perc = pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc =",
"* '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n' %",
"= pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n,",
"i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i",
"in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def",
"Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *",
"test_generator() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing monitor",
"'=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for",
"pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4)",
"(80 * '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '='))",
"items = ['file_%s.csv' % i for i in range(0, n)] perc = pyprind.ProgPercent(len(items))",
"% (80 * '=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80 *",
"test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Force",
"'=')) print('%s\\n' % (80 * '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80",
"'=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"(80 * '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n'",
"update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s' %",
"Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime)",
"<NAME> <<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind",
"test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Percentage",
"test_force_flush(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc",
"* '=')) print('%s\\n' % (80 * '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' %",
"(80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s'",
"= pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n)",
"% (80 * '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 *",
"clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time",
"n)] perc = pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc",
"* '=')) print('%s\\n' % (80 * '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' %",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Basic Percentage",
"= 100 sleeptime = 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for i in",
"test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime) perc.update() print(perc) def",
"__name__ == \"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"function\\n') test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"Python Progress Indicator Utility Author: <NAME> <<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors",
"perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv' % i for i in range(0,",
"in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i in",
"perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update()",
"print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *",
"pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout)",
"* '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n' %",
"for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for",
"Utility Author: <NAME> <<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind",
"perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update()",
"Indicator Generator\\n') test_generator() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"i in range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s' % (80 *",
"\"\"\" import sys import time import pyprind n = 100 sleeptime = 0.02",
"print('%s\\n' % (80 * '=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80",
"'=')) print('%s\\n' % (80 * '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80",
"* '=')) print('%s\\n' % (80 * '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' %",
"test_basic_percent(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc",
"2014-2016 Python Progress Indicator Utility Author: <NAME> <<EMAIL>> License: BSD 3 clause Contributors:",
"time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime)",
"perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc =",
"= ['file_%s.csv' % i for i in range(0, n)] perc = pyprind.ProgPercent(len(items)) for",
"<<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\"",
"% i for i in range(0, n)] perc = pyprind.ProgPercent(len(items)) for i in",
"in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for i in range(n):",
"print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"* '=')) print('%s\\n' % (80 * '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s'",
"in range(0, n)] perc = pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i) def",
"https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import pyprind n = 100 sleeptime =",
"time import pyprind n = 100 sleeptime = 0.02 def test_basic_percent(): perc =",
"print(perc) def test_item_tracking(): items = ['file_%s.csv' % i for i in range(0, n)]",
"for i in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout):",
"* '=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80 * '=')) print('%s\\n'",
"% (80 * '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80 * '='))",
"Force Flush\\n') test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"def test_item_tracking(): items = ['file_%s.csv' % i for i in range(0, n)] perc",
"import sys import time import pyprind n = 100 sleeptime = 0.02 def",
"pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s'",
"'=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import",
"if __name__ == \"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *",
"Author: <NAME> <<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI:",
"= 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update()",
"range(0, n)] perc = pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush():",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing monitor function\\n')",
"def test_force_flush(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval():",
"https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import pyprind",
"pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i in range(n):",
"def test_basic_percent(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update() def test_stdout():",
"test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True)",
"for i in range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s' % (80",
"Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import pyprind n =",
"in range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s' % (80 * '='))",
"perc = pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking():",
"'=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n' % (80",
"test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update() def test_generator():",
"= pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n,",
"100 sleeptime = 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for i in range(n):",
"= pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\":",
"time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True)",
"print('%s\\n' % (80 * '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80",
"\"\"\" <NAME> 2014-2016 Python Progress Indicator Utility Author: <NAME> <<EMAIL>> License: BSD 3",
"stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime)",
"pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items =",
"0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update() def",
"Stream\\n') test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Force Flush\\n')",
"in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in",
"time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n' %",
"print('%s\\n' % (80 * '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80 *",
"'=')) print('%s\\n' % (80 * '=')) print('Testing Basic Percentage Indicator\\n') test_basic_percent() print('\\n%s' %",
"test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing stdout",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing stdout Stream\\n')",
"i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc = pyprind.ProgPercent(n, update_interval=4) for i",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Percentage Indicator Generator\\n')",
"Generator\\n') test_generator() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Update Interval\\n') test_update_interval()",
"in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc = pyprind.ProgPercent(n, monitor=True) for i in",
"== \"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"print('%s\\n' % (80 * '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 *",
"import pyprind n = 100 sleeptime = 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n)",
"'=')) print('%s\\n' % (80 * '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Item Tracking\\n')",
"sleeptime = 0.02 def test_basic_percent(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime)",
"for i in range(0, n)] perc = pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime)",
"% (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing stdout Stream\\n') test_stdout()",
"pyprind.ProgPercent(len(items)) for i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for",
"'=')) print('%s\\n' % (80 * '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80",
"'=')) print('%s\\n' % (80 * '=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' %",
"* '=')) print('%s\\n' % (80 * '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' %",
"(80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s'",
"= pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i",
"perc = pyprind.ProgPercent(n, update_interval=4) for i in range(n): time.sleep(sleeptime) perc.update() if __name__ ==",
"print('%s\\n' % (80 * '=')) print('Testing Force Flush\\n') test_force_flush() print('\\n%s' % (80 *",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Update Interval\\n')",
"(80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Percentage Indicator Generator\\n') test_generator()",
"for i in items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for i",
"print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *",
"range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items = ['file_%s.csv' % i for i",
"Percentage Indicator\\n') test_basic_percent() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"% (80 * '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80 * '='))",
"monitor function\\n') test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"% (80 * '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80 * '='))",
"i in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i",
"(80 * '=')) print('%s\\n' % (80 * '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s'",
"Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing",
"print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Percentage Indicator",
"['file_%s.csv' % i for i in range(0, n)] perc = pyprind.ProgPercent(len(items)) for i",
"time.sleep(sleeptime) perc.update() def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime) def test_monitoring(): perc",
"* '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n' %",
"Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import time import pyprind n",
"'=')) print('Testing Percentage Indicator Generator\\n') test_generator() print('\\n%s' % (80 * '=')) print('%s\\n' %",
"Indicator Utility Author: <NAME> <<EMAIL>> License: BSD 3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository:",
"pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i in",
"sys import time import pyprind n = 100 sleeptime = 0.02 def test_basic_percent():",
"\"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Basic",
"perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime) perc.update(force_flush=True) def test_update_interval(): perc =",
"i in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i in pyprind.prog_percent(range(n), stream=sys.stdout): time.sleep(sleeptime)",
"* '=')) print('Testing monitor function\\n') test_monitoring() print('\\n%s' % (80 * '=')) print('%s\\n' %",
"<NAME> 2014-2016 Python Progress Indicator Utility Author: <NAME> <<EMAIL>> License: BSD 3 clause",
"def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update() def",
"(80 * '=')) print('%s\\n' % (80 * '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s'",
"= pyprind.ProgPercent(n, monitor=True) for i in range(n): time.sleep(sleeptime) perc.update() print(perc) def test_item_tracking(): items",
"import time import pyprind n = 100 sleeptime = 0.02 def test_basic_percent(): perc",
"items: time.sleep(sleeptime) perc.update(item_id=i) def test_force_flush(): perc = pyprind.ProgPercent(n) for i in range(n): time.sleep(sleeptime)",
"range(n): time.sleep(sleeptime) perc.update() if __name__ == \"__main__\": print('\\n%s' % (80 * '=')) print('%s\\n'",
"test_force_flush() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '=')) print('Testing Update",
"test_item_tracking(): items = ['file_%s.csv' % i for i in range(0, n)] perc =",
"(80 * '=')) print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n'",
"stdout Stream\\n') test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 * '='))",
"3 clause Contributors: https://github.com/rasbt/pyprind/graphs/contributors Code Repository: https://github.com/rasbt/pyprind PyPI: https://pypi.python.org/pypi/PyPrind \"\"\" import sys import",
"% (80 * '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '='))",
"(80 * '=')) print('Testing Item Tracking\\n') test_item_tracking() print('\\n%s' % (80 * '=')) print('%s\\n'",
"range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for i in range(n):",
"stream=sys.stdout) for i in range(n): time.sleep(sleeptime) perc.update() def test_generator(): for i in pyprind.prog_percent(range(n),",
"for i in range(n): time.sleep(sleeptime) perc.update() def test_stdout(): perc = pyprind.ProgPercent(n, stream=sys.stdout) for",
"print('Testing stdout Stream\\n') test_stdout() print('\\n%s' % (80 * '=')) print('%s\\n' % (80 *"
] |
[
"= ['00'] zb.extend(message_length) nm_length = zb print nm_length else: nm_length = message_length #",
"0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message",
"+ md5sum + data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print",
"# Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex: %s\" % \\",
"%s\\n - Bytes: %s\\n - Hex: %s\" % \\ (parity.encode('hex'), [ ord(x) for",
"message = packetlength + md5sum + data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex'))",
"\\ ([ ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex'))",
"exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message number of 1 bits",
"x.encode('hex') for x in packetlength ]),16), [ ord(x) for x in packetlength ],",
"mdata = [ x.encode('hex') for x in data ] decodedmessage = [ chr(int(x,16)",
"def __decodeData(self, data): mdata = [ x.encode('hex') for x in data ] decodedmessage",
"- Hex: %s\\n - Bin: %s\" % \\ ([ ord(x) for x in",
"1 bits is ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte",
"1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print \"\\nNM",
"= self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex: %s\"",
"%s\" % [ x.encode('hex') for x in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded",
"getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data",
"not ok\" % num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5()",
"self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16) - 16 -",
"Debug print \"\\nReceived: %d\" % len(received) return received def __getPacketLength(self): packetlength = self.__receiveBytes(2)",
"print \"\\nNM binary: %s\" % nm_binary print \"NM message: \" print nm_message createdmessage",
"# Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM",
"is %s\" % bits[len(bits)-8:] if(num_1bits % 2 == 0): print \"Even number of",
"\"Message number of 1 bits is ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1')",
"binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address, port): try: self.client.connect((address, port))",
"decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print",
"= self.client.recv(amount) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() # Debug",
"\"\\nNM binary: %s\" % nm_binary print \"NM message: \" print nm_message createdmessage =",
"def __getParityByte(self): parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n",
"<= 0xff): print 'True' zb = ['00'] zb.extend(message_length) nm_length = zb print nm_length",
"message_length # Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print",
"counts[0][0] print \"Most commom byte in data is hex: %s\" % self.mostcommonbyte def",
"= self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16) - 16 - 2 -",
"def __getData(self, amount): data = self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n - Bytes:",
"except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() # Debug print \"\\nReceived:",
"def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n - Bytes:",
"%s\" % \\ (data.encode('hex'), [ ord(x) for x in data ], [ x.encode('hex')",
"is ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\"",
"0 else: print \"Odd number of 1 bits (%d), message parity is not",
"nm_md5sum nm_decodedmessage = [ x.encode('hex') for x in decodedmessage] nm_parity = 0x0 nm_message",
"(int(''.join([ x.encode('hex') for x in packetlength ]),16), [ ord(x) for x in packetlength",
"collections # classes class SockClient(object): \"\"\"SockClient for handling the connection to the server\"\"\"",
"- Hex: %s\" % \\ (int(''.join([ x.encode('hex') for x in packetlength ]),16), [",
"% bits[len(bits)-8:] if(num_1bits % 2 == 0): print \"Even number of 1 bits",
"message str: %s\" % createdmessage return createdmessage def getEncryptedMessage(self): print \"Client: Receiving new",
"\"Error sending decoded data: %s\" % e sys.exit(1) print \"Client: Decoded message has",
"print \"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (parity.encode('hex'), [",
"% (message_md5, md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for x in",
"self.mostcommonbyte = counts[0][0] print \"Most commom byte in data is hex: %s\" %",
"\"\"\"SockClient for handling the connection to the server\"\"\" def __init__(self): # Creates a",
"parity byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does not exists!\" else:",
"else: print \"Message number of 1 bits is ODD (%d), checking parity byte...\"",
"print \"\\nNM length: %d - Hex: %s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2]",
"self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def",
"(message_md5, md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for x in data]).most_common()",
"print >> sys.stderr, e self.client.close() sys.exit() # Debug print \"\\nReceived: %d\" % len(received)",
"(len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print \"\\nNM length: %d - Hex: %s\"",
"self.__getParityByte() message = packetlength + md5sum + data + parity binarymessage = (bin(int(message.encode('hex'),",
"ok %s != %s\" % (message_md5, md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([",
"encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded",
"self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata)",
"utf-8 # imports import socket import sys import hashlib import binascii import collections",
"# Debug print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n - Hex: %s\" %",
"md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n -",
"\\ (parity.encode('hex'), [ ord(x) for x in parity ], [ x.encode('hex') for x",
"message parity is not ok\" % num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5):",
"x.encode('hex') for x in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom byte in",
"x in packetlength ]),16), [ ord(x) for x in packetlength ], [ x.encode('hex')",
"for i in range(0, len(hexnmlength), 2)] # Miau por falta de conhecimento como",
"print >> sys.stderr, e sys.exit() def __receiveBytes(self, amount): try: received = self.client.recv(amount) except",
"> 1): print \"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 ==",
"hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print \"\\nNM length: %d -",
"i in range(0, len(hexnmlength), 2)] # Miau por falta de conhecimento como adicionar",
"ord(x) for x in packetlength ], [ x.encode('hex') for x in packetlength]) return",
"connection to the server\"\"\" def __init__(self): # Creates a TCP/IP socket try: self.client",
"in range(0, len(hexnmlength), 2)] # Miau por falta de conhecimento como adicionar 0's",
"len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex') for x in decodedmessage] nm_parity",
"createdmessage = ''.join(nm_message) print \"NM message str: %s\" % createdmessage return createdmessage def",
"16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary print",
"binascii import collections # classes class SockClient(object): \"\"\"SockClient for handling the connection to",
"], [ x.encode('hex') for x in packetlength]) return packetlength def __getMD5Sum(self): md5sum =",
"return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage)",
"(%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:]",
"print \"Parity byte is %s\" % bits[len(bits)-8:] else: print \"Message number of 1",
"of 1 bits (%d), message parity is not ok\" % num_1bits return 1",
"2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex') for x in decodedmessage] nm_parity =",
"sent!\" def getServerResponse(self): print \"Client: Getting server response...\" packetlength = self.__getPacketLength() md5sum =",
"Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x) for x in md5sum ], [",
"nm_message.extend(nm_parity) # Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity =",
"nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary print \"NM message: \"",
"hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum: %s\" %",
"for x in packetlength ]),16) - 16 - 2 - 1) parity =",
"newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5",
"is hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print",
"number of 1 bits is Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print",
"\"NM message str: %s\" % createdmessage return createdmessage def getEncryptedMessage(self): print \"Client: Receiving",
"in data ], [ x.encode('hex') for x in data]) return data def __getParityByte(self):",
"- Bytes: %s\\n - Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x) for x",
"0): print \"Even number of 1 bits (%d), message parity is ok\" %",
"md5sum]) return md5sum def __getData(self, amount): data = self.__receiveBytes(amount) # Debug print \"\\n\\nData:",
"%s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for",
"== %s\" % (message_md5, md5sum) else: print \"Data MD5 sum is NOT ok",
"%s\" % createdmessage return createdmessage def getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength",
"(parity.encode('hex'), [ ord(x) for x in parity ], [ x.encode('hex') for x in",
"- Hex: %s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i in range(0,",
"= (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin:",
"return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16 + len(decodedmessage) +",
"16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity",
"adicionar 0's em 2 bytes hex no python if(nm_length <= 0xff): print 'True'",
"return data def __getParityByte(self): parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n -",
"ok\" % num_1bits return 0 else: print \"Odd number of 1 bits (%d),",
"bits (%d), message parity is ok\" % num_1bits return 0 else: print \"Odd",
"+ 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print",
"x in packetlength ]),16) - 16 - 2 - 1) parity = self.__getParityByte()",
"% num_1bits return 0 else: print \"Odd number of 1 bits (%d), message",
"binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x)",
"import collections # classes class SockClient(object): \"\"\"SockClient for handling the connection to the",
"checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits",
"print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n - Hex: %s\" % \\ (int(''.join([",
"__decodeData(self, data): mdata = [ x.encode('hex') for x in data ] decodedmessage =",
"received def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n -",
"in mdata ] print decodedmessage print \"Decoded data hex: %s\" % [ x.encode('hex')",
"__checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5):",
"de conhecimento como adicionar 0's em 2 bytes hex no python if(nm_length <=",
"__getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s - Hex: %s\"",
"] decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for x in mdata ] print",
"falta de conhecimento como adicionar 0's em 2 bytes hex no python if(nm_length",
">> sys.stderr, e self.client.close() sys.exit() # Debug print \"\\nReceived: %d\" % len(received) return",
"data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n -",
"bits is ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is",
"md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte",
"[ x.encode('hex') for x in packetlength]) return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16)",
"Receiving new message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex')",
"hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5 sum is",
"for x in decodedmessage] nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage)",
"+ 16 + len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3):",
"% nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x",
"% self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s",
"self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error",
"chr(int(x,16) ^ self.cipherkey) for x in mdata ] print decodedmessage print \"Decoded data",
"num_1bits return 0 else: print \"Odd number of 1 bits (%d), message parity",
"decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\"",
"data]) return data def __getParityByte(self): parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n",
"data str: %s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2",
"= nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum: %s\" % md5sum nm_md5sum =",
"%s\" % \\ (md5sum.encode('hex'), [ ord(x) for x in md5sum ], [ x.encode('hex')",
"message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5): print \"Data",
"\" print nm_message createdmessage = ''.join(nm_message) print \"NM message str: %s\" % createdmessage",
"address, port): try: self.client.connect((address, port)) except socket.error, e: print >> sys.stderr, e self.client.close()",
"__getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte = counts[0][0]",
"try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending decoded data: %s\" % e",
"ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey()",
"byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] else: print \"Message",
"x.encode('hex') for x in parity]) return parity def __checkMessageParity(self, bits): num_1bits = bits.count('1')",
"def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client:",
"= [ x.encode('hex') for x in decodedmessage] nm_parity = 0x0 nm_message = []",
"[ x.encode('hex') for x in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str:",
"x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self,",
"16 - 2 - 1) parity = self.__getParityByte() message = packetlength + md5sum",
"ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data",
"%s\\n - Hex: %s\" % \\ (int(''.join([ x.encode('hex') for x in packetlength ]),16),",
"self.client.close() sys.exit() # Debug print \"\\nReceived: %d\" % len(received) return received def __getPacketLength(self):",
"self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address, port): try: self.client.connect((address, port)) except",
"ord(x) for x in parity ], [ x.encode('hex') for x in parity]) return",
"self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) #",
"# classes class SockClient(object): \"\"\"SockClient for handling the connection to the server\"\"\" def",
"parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits %",
"# Miau por falta de conhecimento como adicionar 0's em 2 bytes hex",
"for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return",
"def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client:",
"[] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message nm_binary = (bin(int(''.join(nm_message),",
"(bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary)",
"packetlength ]),16), [ ord(x) for x in packetlength ], [ x.encode('hex') for x",
"message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address, port): try: self.client.connect((address,",
"print \"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\"",
"length: %d - Hex: %s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i",
"packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n -",
"Bytes: %s\\n - Hex: %s\" % \\ (int(''.join([ x.encode('hex') for x in packetlength",
"socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() # Debug print \"\\nReceived: %d\"",
"\"Data MD5 sum is OK %s == %s\" % (message_md5, md5sum) else: print",
"received = self.client.recv(amount) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() #",
"parity]) return parity def __checkMessageParity(self, bits): num_1bits = bits.count('1') # Check if parity",
"decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending decoded data: %s\"",
"binary: %s\" % nm_binary print \"NM message: \" print nm_message createdmessage = ''.join(nm_message)",
"[ x.encode('hex') for x in data]) return data def __getParityByte(self): parity = self.__receiveBytes(1)",
"if(nm_length <= 0xff): print 'True' zb = ['00'] zb.extend(message_length) nm_length = zb print",
"(%d), message parity is not ok\" % num_1bits return 1 def __checkDataMD5Sum(self, data,",
"counts = collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most",
"print \"\\nNM decoded data MD5 sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2] for",
"\"Cipherkey: Int: %s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata",
"message_length = [hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)] # Miau por falta",
"%s == %s\" % (message_md5, md5sum) else: print \"Data MD5 sum is NOT",
"parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n",
"% bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] else: print \"Message number",
"% (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [ x.encode('hex') for x in",
"% num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum",
"for x in mdata ] print decodedmessage print \"Decoded data hex: %s\" %",
"data: %s\" % e sys.exit(1) print \"Client: Decoded message has been successfully sent!\"",
"sys.stderr, e sys.exit() def __receiveBytes(self, amount): try: received = self.client.recv(amount) except socket.error, e:",
"print \"NM message: \" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print",
"\\ (md5sum.encode('hex'), [ ord(x) for x in md5sum ], [ x.encode('hex') for x",
"(self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [ x.encode('hex') for x in data",
"is Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\"",
"(nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)] # Miau",
"md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage",
"parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary:",
"for x in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str: %s\" %",
"Length: %d\\n - Bytes: %s\\n - Hex: %s\" % \\ (int(''.join([ x.encode('hex') for",
"print \"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits % 2 == 0): print",
"sys import hashlib import binascii import collections # classes class SockClient(object): \"\"\"SockClient for",
"2 == 0): print \"Even number of 1 bits (%d), message parity is",
"\"Even number of 1 bits (%d), message parity is ok\" % num_1bits return",
"bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] else: print \"Message number of",
"[ ord(x) for x in parity ], [ x.encode('hex') for x in parity])",
"ok\" % num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data)",
"x in packetlength]) return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print",
"= self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\" createdmessage",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr, e sys.exit() def __receiveBytes(self,",
"\\ (int(''.join([ x.encode('hex') for x in packetlength ]),16), [ ord(x) for x in",
"i in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex') for x",
"for x in data ] decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for x",
"print \"Client: Receiving new message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data =",
"\"Parity byte is %s\" % bits[len(bits)-8:] else: print \"Message number of 1 bits",
"\"\\nReceived: %d\" % len(received) return received def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug",
"bits is Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is",
"1): print \"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0):",
"== 0): print \"Message number of 1 bits is Even (%d), checking parity",
"zb = ['00'] zb.extend(message_length) nm_length = zb print nm_length else: nm_length = message_length",
"[ ord(x) for x in md5sum ], [ x.encode('hex') for x in md5sum])",
"message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending decoded data: %s\" %",
"of 1 bits (%d), message parity is ok\" % num_1bits return 0 else:",
"__getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n",
"__getParityByte(self): parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n -",
"def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum ==",
"(message_md5, md5sum) else: print \"Data MD5 sum is NOT ok %s != %s\"",
"def getServerResponse(self): print \"Client: Getting server response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum()",
"[ x.encode('hex') for x in decodedmessage] nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length)",
"= hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print \"\\nNM length: %d",
"packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x in",
"e sys.exit() def __receiveBytes(self, amount): try: received = self.client.recv(amount) except socket.error, e: print",
"- Bytes: %s\\n - Hex: %s\" % \\ (parity.encode('hex'), [ ord(x) for x",
"^ 0x20 print \"Cipherkey: Int: %s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def",
"= [ chr(int(x,16) ^ self.cipherkey) for x in mdata ] print decodedmessage print",
"hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey:",
"]),16), [ ord(x) for x in packetlength ], [ x.encode('hex') for x in",
"self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16) - 16 - 2 - 1)",
"Sum: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x)",
"is OK %s == %s\" % (message_md5, md5sum) else: print \"Data MD5 sum",
"4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary print \"NM message:",
"nm_decodedmessage = [ x.encode('hex') for x in decodedmessage] nm_parity = 0x0 nm_message =",
"x.encode('hex') for x in data ] decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for",
"socket.error, e: print \"Error sending decoded data: %s\" % e sys.exit(1) print \"Client:",
"\"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin: %s\" % \\ ([ ord(x) for",
"print \"Data MD5 sum is NOT ok %s != %s\" % (message_md5, md5sum)",
"%s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16",
"nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity",
"parity def __checkMessageParity(self, bits): num_1bits = bits.count('1') # Check if parity byte exists",
"print \"Odd number of 1 bits (%d), message parity is not ok\" %",
"return createdmessage def getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength = self.__getPacketLength() md5sum",
"to the server\"\"\" def __init__(self): # Creates a TCP/IP socket try: self.client =",
"amount): data = self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n -",
"\"\\nDecoded data str: %s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length =",
"def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16 + len(decodedmessage) + 1 hexnmlength",
"print 'True' zb = ['00'] zb.extend(message_length) nm_length = zb print nm_length else: nm_length",
"Hex: %s\" % \\ (parity.encode('hex'), [ ord(x) for x in parity ], [",
"decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16 + len(decodedmessage) + 1",
"print nm_md5sum nm_decodedmessage = [ x.encode('hex') for x in decodedmessage] nm_parity = 0x0",
"!= %s\" % (message_md5, md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for",
"print \"Data MD5 sum is OK %s == %s\" % (message_md5, md5sum) else:",
"print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending",
"- Hex: %s\" % \\ (parity.encode('hex'), [ ord(x) for x in parity ],",
"x in md5sum]) return md5sum def __getData(self, amount): data = self.__receiveBytes(amount) # Debug",
"decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16 + len(decodedmessage)",
"= int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s - Hex: %s\" % (self.cipherkey,",
"hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print \"\\nNM length:",
"x.encode('hex') for x in packetlength]) return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) #",
"== message_md5): print \"Data MD5 sum is OK %s == %s\" % (message_md5,",
"x.encode('hex') for x in packetlength ]),16) - 16 - 2 - 1) parity",
"decoded data: %s\" % e sys.exit(1) print \"Client: Decoded message has been successfully",
"Bytes: %s\\n - Hex: %s\" % \\ (parity.encode('hex'), [ ord(x) for x in",
"= self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x in packetlength",
"x in packetlength ], [ x.encode('hex') for x in packetlength]) return packetlength def",
"%s\" % nm_binary print \"NM message: \" print nm_message createdmessage = ''.join(nm_message) print",
"server\"\"\" def __init__(self): # Creates a TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n",
"decodedmessage] nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message:",
"x.encode('hex') for x in md5sum]) return md5sum def __getData(self, amount): data = self.__receiveBytes(amount)",
"print \"NM message str: %s\" % createdmessage return createdmessage def getEncryptedMessage(self): print \"Client:",
"packetlength ], [ x.encode('hex') for x in packetlength]) return packetlength def __getMD5Sum(self): md5sum",
"class SockClient(object): \"\"\"SockClient for handling the connection to the server\"\"\" def __init__(self): #",
"x in data ], [ x.encode('hex') for x in data]) return data def",
"number of 1 bits (%d), message parity is not ok\" % num_1bits return",
"in packetlength ]),16), [ ord(x) for x in packetlength ], [ x.encode('hex') for",
"[ x.encode('hex') for x in parity]) return parity def __checkMessageParity(self, bits): num_1bits =",
"Bin: %s\" % \\ ([ ord(x) for x in message ], message.encode('hex'), binarymessage)",
"x in decodedmessage] nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print",
"([ ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data)",
"nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary",
"a TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >>",
"__getData(self, amount): data = self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n",
"print \"Most commom byte in data is hex: %s\" % self.mostcommonbyte def __getCipherKey(self):",
"message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error,",
"port)) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() def disconnect(self): self.client.close()",
"\"NM message: \" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM",
"conhecimento como adicionar 0's em 2 bytes hex no python if(nm_length <= 0xff):",
"for x in packetlength]) return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug",
"[hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)] # Miau por falta de conhecimento",
"decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str: %s\" % decodedmessage return decodedmessage",
"[''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary = (bin(int(''.join(nm_message),",
"print \"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin: %s\" % \\ ([ ord(x)",
"in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str: %s\" % decodedmessage return",
"if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message number of 1 bits is Even",
"decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except",
"data): counts = collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte = counts[0][0] print",
"self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending decoded data: %s\" % e sys.exit(1)",
"], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address, port): try:",
"def __checkMessageParity(self, bits): num_1bits = bits.count('1') # Check if parity byte exists if(int(bits[len(bits)-8:])",
"self.client.connect((address, port)) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() def disconnect(self):",
"if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2",
"Decoded message has been successfully sent!\" def getServerResponse(self): print \"Client: Getting server response...\"",
"__checkMessageParity(self, bits): num_1bits = bits.count('1') # Check if parity byte exists if(int(bits[len(bits)-8:]) >",
"% \\ (parity.encode('hex'), [ ord(x) for x in parity ], [ x.encode('hex') for",
"def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte =",
"hashlib import binascii import collections # classes class SockClient(object): \"\"\"SockClient for handling the",
"md5sum) else: print \"Data MD5 sum is NOT ok %s != %s\" %",
"print \"\\nDecoded data str: %s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length",
"%d - Hex: %s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i in",
"4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin: %s\" % \\ ([",
"md5sum ], [ x.encode('hex') for x in md5sum]) return md5sum def __getData(self, amount):",
"len(hexnmlength), 2)] # Miau por falta de conhecimento como adicionar 0's em 2",
"nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message))",
"], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata):",
"\"Decoded data hex: %s\" % [ x.encode('hex') for x in decodedmessage] decodedmessage =",
"parity ], [ x.encode('hex') for x in parity]) return parity def __checkMessageParity(self, bits):",
"= self.__getParityByte() message = packetlength + md5sum + data + parity binarymessage =",
"print \"\\nNM binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity",
"try: self.client.connect((address, port)) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() def",
"x in mdata ] print decodedmessage print \"Decoded data hex: %s\" % [",
"* 4) print \"\\nNM binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity =",
"in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4)",
"self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr, e sys.exit() def",
"% (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)] #",
"%s\" % bits[len(bits)-8:] if(num_1bits % 2 == 0): print \"Even number of 1",
"num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum =",
"self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16)",
"else: nm_length = message_length # Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum",
"% bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits % 2 ==",
"+ len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength =",
"# Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n - Hex: %s\" % \\",
"hexnmlength) message_length = [hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)] # Miau por",
"MD5 sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2] for i in range(0, len(md5sum),",
"= ''.join(nm_message) print \"NM message str: %s\" % createdmessage return createdmessage def getEncryptedMessage(self):",
"(bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin: %s\"",
"% decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16 +",
"sys.exit(1) print \"Client: Decoded message has been successfully sent!\" def getServerResponse(self): print \"Client:",
"TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr,",
"message_md5): print \"Data MD5 sum is OK %s == %s\" % (message_md5, md5sum)",
"md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16) -",
"sending decoded data: %s\" % e sys.exit(1) print \"Client: Decoded message has been",
"<gh_stars>0 #!/usr/bin/python # coding: utf-8 # imports import socket import sys import hashlib",
"nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)]",
"% \\ (md5sum.encode('hex'), [ ord(x) for x in md5sum ], [ x.encode('hex') for",
"= [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary =",
"= self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16) - 16",
"sys.stderr, e self.client.close() sys.exit() # Debug print \"\\nReceived: %d\" % len(received) return received",
"data ], [ x.encode('hex') for x in data]) return data def __getParityByte(self): parity",
"message parity is ok\" % num_1bits return 0 else: print \"Odd number of",
"message: \" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary:",
"nm_length = zb print nm_length else: nm_length = message_length # Fim do Miau",
"message has been successfully sent!\" def getServerResponse(self): print \"Client: Getting server response...\" packetlength",
"Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n - Hex: %s\" % \\",
"md5sum def __getData(self, amount): data = self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n -",
"createdmessage def getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength = self.__getPacketLength() md5sum =",
"exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1') %",
"data): mdata = [ x.encode('hex') for x in data ] decodedmessage = [",
"nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum:",
"for x in parity ], [ x.encode('hex') for x in parity]) return parity",
"\"Client: Getting server response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([",
"(data.encode('hex'), [ ord(x) for x in data ], [ x.encode('hex') for x in",
"self.client.recv(amount) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit() # Debug print",
"== 3): hexnmlength = '0'+hexnmlength print \"\\nNM length: %d - Hex: %s\" %",
"%s\" % bits[len(bits)-8:] else: print \"Message number of 1 bits is ODD (%d),",
"= newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5 sum is OK %s ==",
"does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message number of",
"nm_length = 2 + 16 + len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if",
"]),16) - 16 - 2 - 1) parity = self.__getParityByte() message = packetlength",
"[md5sum[i:i+2] for i in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex')",
"return data def connect(self, address, port): try: self.client.connect((address, port)) except socket.error, e: print",
"do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data",
"Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" %",
"= bits.count('1') # Check if parity byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity",
"collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom byte",
"self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return",
"\"Client: Receiving new message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([",
"Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (parity.encode('hex'),",
"^ self.cipherkey) for x in mdata ] print decodedmessage print \"Decoded data hex:",
"newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5 sum is OK",
"\"\\nNM length: %d - Hex: %s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for",
"data def __getParityByte(self): parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n - Bytes:",
"len(received) return received def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length:",
"for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def",
"try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr, e sys.exit()",
"[ ord(x) for x in packetlength ], [ x.encode('hex') for x in packetlength])",
"bits): num_1bits = bits.count('1') # Check if parity byte exists if(int(bits[len(bits)-8:]) > 1):",
"Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded",
"imports import socket import sys import hashlib import binascii import collections # classes",
"classes class SockClient(object): \"\"\"SockClient for handling the connection to the server\"\"\" def __init__(self):",
"print \"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0): print",
"''.join(nm_message) print \"NM message str: %s\" % createdmessage return createdmessage def getEncryptedMessage(self): print",
"in packetlength]) return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5",
"data MD5 sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2] for i in range(0,",
"= self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n - Hex: %s\"",
"Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data MD5",
"byte does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message number",
"parity is ok\" % num_1bits return 0 else: print \"Odd number of 1",
"- 1) parity = self.__getParityByte() message = packetlength + md5sum + data +",
"self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n - Hex: %s\"",
"= 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print",
"for x in packetlength ]),16), [ ord(x) for x in packetlength ], [",
"in packetlength ], [ x.encode('hex') for x in packetlength]) return packetlength def __getMD5Sum(self):",
"message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self,",
"- Bytes: %s\\n - Hex: %s\" % \\ (data.encode('hex'), [ ord(x) for x",
"nm_message createdmessage = ''.join(nm_message) print \"NM message str: %s\" % createdmessage return createdmessage",
"= ''.join(decodedmessage) print \"\\nDecoded data str: %s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self,",
"md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum: %s\" % md5sum nm_md5sum",
"\"NM message: \" print nm_message createdmessage = ''.join(nm_message) print \"NM message str: %s\"",
"2 == 0): print \"Message number of 1 bits is Even (%d), checking",
"decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str: %s\" % decodedmessage return decodedmessage def",
"0xff): print 'True' zb = ['00'] zb.extend(message_length) nm_length = zb print nm_length else:",
"x.encode('hex') for x in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str: %s\"",
"[nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity",
"for x in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message))",
"print decodedmessage print \"Decoded data hex: %s\" % [ x.encode('hex') for x in",
"%s\\n - Hex: %s\" % \\ (data.encode('hex'), [ ord(x) for x in data",
"nm_md5sum = [md5sum[i:i+2] for i in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage =",
"packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n -",
"Hex: %s\\n - Bin: %s\" % \\ ([ ord(x) for x in message",
"str: %s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage): nm_length = 2 +",
"nm_length else: nm_length = message_length # Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage)",
"(md5sum.encode('hex'), [ ord(x) for x in md5sum ], [ x.encode('hex') for x in",
"x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data",
"% md5sum nm_md5sum = [md5sum[i:i+2] for i in range(0, len(md5sum), 2)] print nm_md5sum",
"0x20 print \"Cipherkey: Int: %s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self,",
"Miau por falta de conhecimento como adicionar 0's em 2 bytes hex no",
"= (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\" % nm_binary nm_parity =",
"connect(self, address, port): try: self.client.connect((address, port)) except socket.error, e: print >> sys.stderr, e",
"try: received = self.client.recv(amount) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit()",
"for x in data ], [ x.encode('hex') for x in data]) return data",
"\"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message",
"coding: utf-8 # imports import socket import sys import hashlib import binascii import",
"data ] decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for x in mdata ]",
"decoded data MD5 sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2] for i in",
"nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4)",
"- Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x) for x in md5sum ],",
"nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) # Recheck",
"MD5 sum is OK %s == %s\" % (message_md5, md5sum) else: print \"Data",
"number of 1 bits is ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print",
"nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \"",
"packetlength]) return packetlength def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum:",
"__init__(self): # Creates a TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error,",
"- 16 - 2 - 1) parity = self.__getParityByte() message = packetlength +",
"print \"Error sending decoded data: %s\" % e sys.exit(1) print \"Client: Decoded message",
"self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex: %s\" %",
"%s\\n - Hex: %s\" % \\ (parity.encode('hex'), [ ord(x) for x in parity",
"is NOT ok %s != %s\" % (message_md5, md5sum) def __getMostCommonByte(self, data): counts",
"number of 1 bits (%d), message parity is ok\" % num_1bits return 0",
"nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\" % nm_binary nm_parity",
"% bits[len(bits)-8:] else: print \"Message number of 1 bits is ODD (%d), checking",
"\"Message number of 1 bits is Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1')",
"hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [ x.encode('hex') for x in data ]",
"1 bits is Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte",
"return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage):",
"= [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity) # Recheck message",
"print \"Decoded data hex: %s\" % [ x.encode('hex') for x in decodedmessage] decodedmessage",
"def __receiveBytes(self, amount): try: received = self.client.recv(amount) except socket.error, e: print >> sys.stderr,",
"def __init__(self): # Creates a TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except",
"%s\" % \\ ([ ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage)",
"# Debug print \"\\nReceived: %d\" % len(received) return received def __getPacketLength(self): packetlength =",
"\"Most commom byte in data is hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey",
"data = self.__getData(int(''.join([ x.encode('hex') for x in packetlength ]),16) - 16 - 2",
"* 4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin: %s\" % \\",
"server response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for",
"Debug print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n - Hex: %s\" % \\",
"], [ x.encode('hex') for x in parity]) return parity def __checkMessageParity(self, bits): num_1bits",
"([ ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return",
"= self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print",
"in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def",
"''.join(decodedmessage) print \"\\nDecoded data str: %s\" % decodedmessage return decodedmessage def __createDecodedMessagePacket(self, decodedmessage):",
"nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) *",
"parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex:",
"no python if(nm_length <= 0xff): print 'True' zb = ['00'] zb.extend(message_length) nm_length =",
"2 - 1) parity = self.__getParityByte() message = packetlength + md5sum + data",
"% createdmessage return createdmessage def getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength =",
"e: print >> sys.stderr, e sys.exit() def __receiveBytes(self, amount): try: received = self.client.recv(amount)",
"byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does not exists!\" else: if(bits[:len(bits)-8].count('1')",
"else: print \"Odd number of 1 bits (%d), message parity is not ok\"",
"= [hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)] # Miau por falta de",
"is ok\" % num_1bits return 0 else: print \"Odd number of 1 bits",
"len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength",
"\"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (md5sum.encode('hex'), [",
"decodedmessage print \"Decoded data hex: %s\" % [ x.encode('hex') for x in decodedmessage]",
"'True' zb = ['00'] zb.extend(message_length) nm_length = zb print nm_length else: nm_length =",
"\" print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\"",
"decodedmessage): print \"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded",
"%s\" % \\ (parity.encode('hex'), [ ord(x) for x in parity ], [ x.encode('hex')",
"\"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try:",
"%s\" % e sys.exit(1) print \"Client: Decoded message has been successfully sent!\" def",
"self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary print \"NM message: \" print nm_message",
"parity = self.__getParityByte() message = packetlength + md5sum + data + parity binarymessage",
"socket import sys import hashlib import binascii import collections # classes class SockClient(object):",
"= self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n - Hex:",
"message: \" print nm_message createdmessage = ''.join(nm_message) print \"NM message str: %s\" %",
"%s\" % md5sum nm_md5sum = [md5sum[i:i+2] for i in range(0, len(md5sum), 2)] print",
"data def connect(self, address, port): try: self.client.connect((address, port)) except socket.error, e: print >>",
"x in parity ], [ x.encode('hex') for x in parity]) return parity def",
"is %s\" % bits[len(bits)-8:] else: print \"Message number of 1 bits is ODD",
"bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits % 2 == 0):",
"%s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int:",
"print \"\\n\\nData: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (data.encode('hex'), [",
"= self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in nm_parity)] nm_message.extend(nm_parity)",
"handling the connection to the server\"\"\" def __init__(self): # Creates a TCP/IP socket",
"print \"NM message: \" print nm_message createdmessage = ''.join(nm_message) print \"NM message str:",
"nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2]",
"return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest()",
"response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x",
"bits (%d), message parity is not ok\" % num_1bits return 1 def __checkDataMD5Sum(self,",
"% nm_binary print \"NM message: \" print nm_message createdmessage = ''.join(nm_message) print \"NM",
"Creates a TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print",
"= (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" %",
"the connection to the server\"\"\" def __init__(self): # Creates a TCP/IP socket try:",
"nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\" % nm_binary",
"print nm_message createdmessage = ''.join(nm_message) print \"NM message str: %s\" % createdmessage return",
"checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] else:",
"%s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [",
"= [ x.encode('hex') for x in data ] decodedmessage = [ chr(int(x,16) ^",
"%s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i in range(0, len(hexnmlength), 2)]",
"in data ] decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for x in mdata",
"+ parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n - Hex:",
"self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self,",
"for x in md5sum ], [ x.encode('hex') for x in md5sum]) return md5sum",
"return received def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n",
"\"Client: Decoded message has been successfully sent!\" def getServerResponse(self): print \"Client: Getting server",
"], [ x.encode('hex') for x in data]) return data def __getParityByte(self): parity =",
"num_1bits = bits.count('1') # Check if parity byte exists if(int(bits[len(bits)-8:]) > 1): print",
"sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2] for i in range(0, len(md5sum), 2)]",
"been successfully sent!\" def getServerResponse(self): print \"Client: Getting server response...\" packetlength = self.__getPacketLength()",
"2)] # Miau por falta de conhecimento como adicionar 0's em 2 bytes",
"return parity def __checkMessageParity(self, bits): num_1bits = bits.count('1') # Check if parity byte",
"data = self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n - Hex:",
"socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr, e",
"self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n - Hex: %s\"",
"byte is %s\" % bits[len(bits)-8:] else: print \"Message number of 1 bits is",
"nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\"",
"in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom byte in data is hex:",
"packetlength + md5sum + data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4)",
"\"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits % 2 == 0): print \"Even",
"[ x.encode('hex') for x in data ] decodedmessage = [ chr(int(x,16) ^ self.cipherkey)",
"import sys import hashlib import binascii import collections # classes class SockClient(object): \"\"\"SockClient",
"in decodedmessage] nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM",
"message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for x",
"], [ x.encode('hex') for x in md5sum]) return md5sum def __getData(self, amount): data",
"port): try: self.client.connect((address, port)) except socket.error, e: print >> sys.stderr, e self.client.close() sys.exit()",
"decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for x in mdata ] print decodedmessage",
"hexnmlength = '0'+hexnmlength print \"\\nNM length: %d - Hex: %s\" % (nm_length, hexnmlength)",
"int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:])",
"\"Odd number of 1 bits (%d), message parity is not ok\" % num_1bits",
"= packetlength + md5sum + data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) *",
"data def getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print",
"byte in data is hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16)",
"in parity ], [ x.encode('hex') for x in parity]) return parity def __checkMessageParity(self,",
"__receiveBytes(self, amount): try: received = self.client.recv(amount) except socket.error, e: print >> sys.stderr, e",
"not exists!\" else: if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message number of 1",
"if(num_1bits % 2 == 0): print \"Even number of 1 bits (%d), message",
"4) print \"\\nNM binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity]",
"else: print \"Data MD5 sum is NOT ok %s != %s\" % (message_md5,",
"parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] else: print",
"- Hex: %s\" % \\ (data.encode('hex'), [ ord(x) for x in data ],",
"md5sum = newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5 sum is OK %s",
"e: print >> sys.stderr, e self.client.close() sys.exit() # Debug print \"\\nReceived: %d\" %",
"Hex: %s\" % \\ (int(''.join([ x.encode('hex') for x in packetlength ]),16), [ ord(x)",
"x in data]) return data def __getParityByte(self): parity = self.__receiveBytes(1) # Debug print",
"parity is not ok\" % num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5",
"if (len(hexnmlength) == 3): hexnmlength = '0'+hexnmlength print \"\\nNM length: %d - Hex:",
"[ ord(x) for x in data ], [ x.encode('hex') for x in data])",
"except socket.error, e: print \"Error sending decoded data: %s\" % e sys.exit(1) print",
"md5sum nm_md5sum = [md5sum[i:i+2] for i in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage",
"nm_binary print \"NM message: \" print nm_message createdmessage = ''.join(nm_message) print \"NM message",
"getDecodedMessage(self, encryptedMessagedata): decodedmessage = self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating",
"sum is NOT ok %s != %s\" % (message_md5, md5sum) def __getMostCommonByte(self, data):",
"in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address,",
"if(md5sum == message_md5): print \"Data MD5 sum is OK %s == %s\" %",
"1 def __checkDataMD5Sum(self, data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum",
"bits[len(bits)-8:] else: print \"Message number of 1 bits is ODD (%d), checking parity",
"byte is %s\" % bits[len(bits)-8:] if(num_1bits % 2 == 0): print \"Even number",
"\"\\n\\nPacket Length: %d\\n - Bytes: %s\\n - Hex: %s\" % \\ (int(''.join([ x.encode('hex')",
"self.cipherkey) for x in mdata ] print decodedmessage print \"Decoded data hex: %s\"",
"3): hexnmlength = '0'+hexnmlength print \"\\nNM length: %d - Hex: %s\" % (nm_length,",
"for x in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom byte in data",
"except socket.error, e: print >> sys.stderr, e sys.exit() def __receiveBytes(self, amount): try: received",
"% \\ ([ ord(x) for x in message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data,",
"0): print \"Message number of 1 bits is Even (%d), checking parity byte...\"",
"['00'] zb.extend(message_length) nm_length = zb print nm_length else: nm_length = message_length # Fim",
"message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage",
"of 1 bits is Even (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity",
"for x in data]) return data def __getParityByte(self): parity = self.__receiveBytes(1) # Debug",
"else: if(bits[:len(bits)-8].count('1') % 2 == 0): print \"Message number of 1 bits is",
"Int: %s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata =",
"+ data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n",
"%s != %s\" % (message_md5, md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex')",
"hex: %s\" % [ x.encode('hex') for x in decodedmessage] decodedmessage = ''.join(decodedmessage) print",
"self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address, port): try: self.client.connect((address, port)) except socket.error,",
"%d\" % len(received) return received def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print",
"= self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary print \"NM message: \" print",
"is not ok\" % num_1bits return 1 def __checkDataMD5Sum(self, data, message_md5): newmd5 =",
"nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity = [''.join('{:02x}'.format(x) for x in",
"x.encode('hex') for x in decodedmessage] nm_parity = 0x0 nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum)",
"= 2 + 16 + len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength)",
"16 + len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) == 3): hexnmlength",
"= self.__receiveBytes(2) # Debug print \"\\n\\nPacket Length: %d\\n - Bytes: %s\\n - Hex:",
"return md5sum def __getData(self, amount): data = self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n",
"#!/usr/bin/python # coding: utf-8 # imports import socket import sys import hashlib import",
"NOT ok %s != %s\" % (message_md5, md5sum) def __getMostCommonByte(self, data): counts =",
"print nm_length else: nm_length = message_length # Fim do Miau nm_newmd5 = hashlib.md5()",
"range(0, len(hexnmlength), 2)] # Miau por falta de conhecimento como adicionar 0's em",
"como adicionar 0's em 2 bytes hex no python if(nm_length <= 0xff): print",
"%s\\n - Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x) for x in md5sum",
"print \"Even number of 1 bits (%d), message parity is ok\" % num_1bits",
"sum is OK %s == %s\" % (message_md5, md5sum) else: print \"Data MD5",
"1) parity = self.__getParityByte() message = packetlength + md5sum + data + parity",
"== 0): print \"Even number of 1 bits (%d), message parity is ok\"",
"self.__decodeData(encryptedMessagedata) return decodedmessage def sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\" createdmessage =",
"getServerResponse(self): print \"Client: Getting server response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data",
"\"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending decoded",
"in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex') for x in",
"import binascii import collections # classes class SockClient(object): \"\"\"SockClient for handling the connection",
"Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (data.encode('hex'),",
"for x in md5sum]) return md5sum def __getData(self, amount): data = self.__receiveBytes(amount) #",
"x.encode('hex') for x in data]) return data def __getParityByte(self): parity = self.__receiveBytes(1) #",
"commom byte in data is hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey =",
"Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print",
"0's em 2 bytes hex no python if(nm_length <= 0xff): print 'True' zb",
"\"\\nNM binary: %s\" % nm_binary nm_parity = self.__checkMessageParity(nm_binary) nm_parity = [nm_parity] nm_parity =",
"# coding: utf-8 # imports import socket import sys import hashlib import binascii",
"python if(nm_length <= 0xff): print 'True' zb = ['00'] zb.extend(message_length) nm_length = zb",
"in packetlength ]),16) - 16 - 2 - 1) parity = self.__getParityByte() message",
"for x in packetlength ], [ x.encode('hex') for x in packetlength]) return packetlength",
"Check if parity byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does not",
"data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom byte in data is hex: %s\"",
"% len(received) return received def __getPacketLength(self): packetlength = self.__receiveBytes(2) # Debug print \"\\n\\nPacket",
"sys.exit() # Debug print \"\\nReceived: %d\" % len(received) return received def __getPacketLength(self): packetlength",
"sendDecodedMessage(self, decodedmessage): print \"Client: Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending",
"byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" % bits[len(bits)-8:] if(num_1bits % 2",
"(%d), message parity is ok\" % num_1bits return 0 else: print \"Odd number",
"new message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex') for",
"nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum: %s\" % md5sum",
"- Bytes: %s\\n - Hex: %s\" % \\ (int(''.join([ x.encode('hex') for x in",
"- Bin: %s\" % \\ ([ ord(x) for x in message ], message.encode('hex'),",
"# imports import socket import sys import hashlib import binascii import collections #",
"def getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum()",
"* 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary print \"NM",
"\"\\n\\nParity: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (parity.encode('hex'), [ ord(x)",
"print \"Message number of 1 bits is Even (%d), checking parity byte...\" %",
"%d\\n - Bytes: %s\\n - Hex: %s\" % \\ (int(''.join([ x.encode('hex') for x",
"newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5 sum is OK %s == %s\"",
"- Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [ x.encode('hex')",
"= zb print nm_length else: nm_length = message_length # Fim do Miau nm_newmd5",
"%s\\n - Bytes: %s\\n - Hex: %s\" % \\ (data.encode('hex'), [ ord(x) for",
"print \"\\nReceived: %d\" % len(received) return received def __getPacketLength(self): packetlength = self.__receiveBytes(2) #",
"in parity]) return parity def __checkMessageParity(self, bits): num_1bits = bits.count('1') # Check if",
"%s\" % (message_md5, md5sum) else: print \"Data MD5 sum is NOT ok %s",
"sys.exit() def __receiveBytes(self, amount): try: received = self.client.recv(amount) except socket.error, e: print >>",
"% [ x.encode('hex') for x in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data",
"OK %s == %s\" % (message_md5, md5sum) else: print \"Data MD5 sum is",
"x in md5sum ], [ x.encode('hex') for x in md5sum]) return md5sum def",
"data is hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20",
"print \"Client: Decoded message has been successfully sent!\" def getServerResponse(self): print \"Client: Getting",
"Getting server response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data = self.__getData(int(''.join([ x.encode('hex')",
"%s\" % \\ (int(''.join([ x.encode('hex') for x in packetlength ]),16), [ ord(x) for",
"= [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message nm_binary =",
"createdmessage return createdmessage def getEncryptedMessage(self): print \"Client: Receiving new message...\" packetlength = self.__getPacketLength()",
"[ chr(int(x,16) ^ self.cipherkey) for x in mdata ] print decodedmessage print \"Decoded",
"md5sum.encode('hex')) return data def connect(self, address, port): try: self.client.connect((address, port)) except socket.error, e:",
"2 + 16 + len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:] if (len(hexnmlength) ==",
"the server\"\"\" def __init__(self): # Creates a TCP/IP socket try: self.client = socket.socket(socket.AF_INET,",
"= hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5): print \"Data MD5 sum",
"in data is hex: %s\" % self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^",
"x in nm_parity)] nm_message.extend(nm_parity) # Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) *",
"ord(x) for x in data ], [ x.encode('hex') for x in data]) return",
"def __getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes:",
"% (message_md5, md5sum) else: print \"Data MD5 sum is NOT ok %s !=",
"for x in parity]) return parity def __checkMessageParity(self, bits): num_1bits = bits.count('1') #",
"data hex: %s\" % [ x.encode('hex') for x in decodedmessage] decodedmessage = ''.join(decodedmessage)",
"binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) self.__getMostCommonByte(data) self.__getCipherKey() return data def getDecodedMessage(self, encryptedMessagedata): decodedmessage =",
"SockClient(object): \"\"\"SockClient for handling the connection to the server\"\"\" def __init__(self): # Creates",
"\"Data MD5 sum is NOT ok %s != %s\" % (message_md5, md5sum) def",
"e self.client.close() sys.exit() # Debug print \"\\nReceived: %d\" % len(received) return received def",
"bits[len(bits)-8:] if(num_1bits % 2 == 0): print \"Even number of 1 bits (%d),",
"nm_message = [] nm_message.extend(nm_length) nm_message.extend(nm_md5sum) nm_message.extend(nm_decodedmessage) print \"NM message: \" print nm_message nm_binary",
"%s\\n - Bin: %s\" % \\ ([ ord(x) for x in message ],",
"%s\" % (message_md5, md5sum) def __getMostCommonByte(self, data): counts = collections.Counter([ x.encode('hex') for x",
"[ x.encode('hex') for x in md5sum]) return md5sum def __getData(self, amount): data =",
"__getMD5Sum(self): md5sum = self.__receiveBytes(16) # Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n",
"Hex: %s\" % \\ (data.encode('hex'), [ ord(x) for x in data ], [",
"successfully sent!\" def getServerResponse(self): print \"Client: Getting server response...\" packetlength = self.__getPacketLength() md5sum",
"in data]) return data def __getParityByte(self): parity = self.__receiveBytes(1) # Debug print \"\\n\\nParity:",
"print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (md5sum.encode('hex'),",
"x in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom byte in data is",
"bytes hex no python if(nm_length <= 0xff): print 'True' zb = ['00'] zb.extend(message_length)",
"self.__receiveBytes(amount) # Debug print \"\\n\\nData: %s\\n - Bytes: %s\\n - Hex: %s\" %",
"print nm_message nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) print \"\\nNM binary: %s\" %",
"# Recheck message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary)",
"= counts[0][0] print \"Most commom byte in data is hex: %s\" % self.mostcommonbyte",
"amount): try: received = self.client.recv(amount) except socket.error, e: print >> sys.stderr, e self.client.close()",
"16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n - Bin: %s\" %",
"print \"Message number of 1 bits is ODD (%d), checking parity byte...\" %",
"createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e:",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr, e sys.exit() def __receiveBytes(self, amount):",
"in md5sum]) return md5sum def __getData(self, amount): data = self.__receiveBytes(amount) # Debug print",
"# Creates a TCP/IP socket try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e:",
"socket.error, e: print >> sys.stderr, e sys.exit() def __receiveBytes(self, amount): try: received =",
"% 2 == 0): print \"Even number of 1 bits (%d), message parity",
"% 2 == 0): print \"Message number of 1 bits is Even (%d),",
"binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage: %s\\n - Hex: %s\\n -",
"\\ (data.encode('hex'), [ ord(x) for x in data ], [ x.encode('hex') for x",
">> sys.stderr, e sys.exit() def __receiveBytes(self, amount): try: received = self.client.recv(amount) except socket.error,",
"# Debug print \"\\n\\nMD5 Sum: %s\\n - Bytes: %s\\n - Hex: %s\" %",
"x in data ] decodedmessage = [ chr(int(x,16) ^ self.cipherkey) for x in",
"= [md5sum[i:i+2] for i in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [",
"message ], message.encode('hex'), binarymessage) self.__checkMessageParity(binarymessage) self.__checkDataMD5Sum(data, md5sum.encode('hex')) return data def connect(self, address, port):",
"ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity byte is %s\" %",
"md5sum + data + parity binarymessage = (bin(int(message.encode('hex'), 16))[2:]).zfill(len(message.encode('hex')) * 4) print \"\\n\\nMessage:",
"in md5sum ], [ x.encode('hex') for x in md5sum]) return md5sum def __getData(self,",
"hex no python if(nm_length <= 0xff): print 'True' zb = ['00'] zb.extend(message_length) nm_length",
"if parity byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does not exists!\"",
"% e sys.exit(1) print \"Client: Decoded message has been successfully sent!\" def getServerResponse(self):",
"self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s - Hex: %s\" %",
"Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [ x.encode('hex') for",
"2 bytes hex no python if(nm_length <= 0xff): print 'True' zb = ['00']",
"def connect(self, address, port): try: self.client.connect((address, port)) except socket.error, e: print >> sys.stderr,",
"% \\ (data.encode('hex'), [ ord(x) for x in data ], [ x.encode('hex') for",
"em 2 bytes hex no python if(nm_length <= 0xff): print 'True' zb =",
"import socket import sys import hashlib import binascii import collections # classes class",
"%s\\n - Bytes: %s\\n - Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x) for",
"\"\\n\\nData: %s\\n - Bytes: %s\\n - Hex: %s\" % \\ (data.encode('hex'), [ ord(x)",
"1 bits (%d), message parity is not ok\" % num_1bits return 1 def",
"of 1 bits is ODD (%d), checking parity byte...\" % bits[:len(bits)-8].count('1') print \"Parity",
"- 2 - 1) parity = self.__getParityByte() message = packetlength + md5sum +",
"self.mostcommonbyte def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s -",
"str: %s\" % createdmessage return createdmessage def getEncryptedMessage(self): print \"Client: Receiving new message...\"",
"(bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM binary: %s\" % nm_binary",
"decodedmessage): nm_length = 2 + 16 + len(decodedmessage) + 1 hexnmlength = hex(nm_length)[2:]",
"def __getCipherKey(self): self.cipherkey = int(self.mostcommonbyte,16) ^ 0x20 print \"Cipherkey: Int: %s - Hex:",
"range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex') for x in decodedmessage]",
"e sys.exit(1) print \"Client: Decoded message has been successfully sent!\" def getServerResponse(self): print",
"zb print nm_length else: nm_length = message_length # Fim do Miau nm_newmd5 =",
"print \"Cipherkey: Int: %s - Hex: %s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data):",
"data, message_md5): newmd5 = hashlib.md5() newmd5.update(data) md5sum = newmd5.hexdigest() if(md5sum == message_md5): print",
"Bytes: %s\\n - Hex: %s\" % \\ (md5sum.encode('hex'), [ ord(x) for x in",
"%s\" % (self.cipherkey, hex(self.cipherkey)[2:]) def __decodeData(self, data): mdata = [ x.encode('hex') for x",
"x in parity]) return parity def __checkMessageParity(self, bits): num_1bits = bits.count('1') # Check",
"'0'+hexnmlength print \"\\nNM length: %d - Hex: %s\" % (nm_length, hexnmlength) message_length =",
"zb.extend(message_length) nm_length = zb print nm_length else: nm_length = message_length # Fim do",
"import hashlib import binascii import collections # classes class SockClient(object): \"\"\"SockClient for handling",
"= '0'+hexnmlength print \"\\nNM length: %d - Hex: %s\" % (nm_length, hexnmlength) message_length",
"nm_length = message_length # Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum =",
"%s\\n - Hex: %s\\n - Bin: %s\" % \\ ([ ord(x) for x",
"] print decodedmessage print \"Decoded data hex: %s\" % [ x.encode('hex') for x",
"x in decodedmessage] decodedmessage = ''.join(decodedmessage) print \"\\nDecoded data str: %s\" % decodedmessage",
"has been successfully sent!\" def getServerResponse(self): print \"Client: Getting server response...\" packetlength =",
"Bytes: %s\\n - Hex: %s\" % \\ (data.encode('hex'), [ ord(x) for x in",
"MD5 sum is NOT ok %s != %s\" % (message_md5, md5sum) def __getMostCommonByte(self,",
"por falta de conhecimento como adicionar 0's em 2 bytes hex no python",
"% \\ (int(''.join([ x.encode('hex') for x in packetlength ]),16), [ ord(x) for x",
"__createDecodedMessagePacket(self, decodedmessage): nm_length = 2 + 16 + len(decodedmessage) + 1 hexnmlength =",
"bits.count('1') # Check if parity byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte",
"mdata ] print decodedmessage print \"Decoded data hex: %s\" % [ x.encode('hex') for",
"packetlength ]),16) - 16 - 2 - 1) parity = self.__getParityByte() message =",
"return 0 else: print \"Odd number of 1 bits (%d), message parity is",
"print \"Client: Getting server response...\" packetlength = self.__getPacketLength() md5sum = self.__getMD5Sum() data =",
"1 bits (%d), message parity is ok\" % num_1bits return 0 else: print",
"e: print \"Error sending decoded data: %s\" % e sys.exit(1) print \"Client: Decoded",
"for handling the connection to the server\"\"\" def __init__(self): # Creates a TCP/IP",
"= message_length # Fim do Miau nm_newmd5 = hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest()",
"Sending decoded message...\" try: self.client.send(createdmessage.decode('hex')) except socket.error, e: print \"Error sending decoded data:",
"socket.SOCK_STREAM) except socket.error, e: print >> sys.stderr, e sys.exit() def __receiveBytes(self, amount): try:",
"for i in range(0, len(md5sum), 2)] print nm_md5sum nm_decodedmessage = [ x.encode('hex') for",
"# Check if parity byte exists if(int(bits[len(bits)-8:]) > 1): print \"Parity byte does",
"= collections.Counter([ x.encode('hex') for x in data]).most_common() self.mostcommonbyte = counts[0][0] print \"Most commom",
"message parity nm_binary = (bin(int(''.join(nm_message), 16))[2:]).zfill(len(''.join(nm_message)) * 4) nm_parity = self.__checkMessageParity(nm_binary) print \"\\nNM",
"= hashlib.md5() nm_newmd5.update(decodedmessage) md5sum = nm_newmd5.hexdigest() print \"\\nNM decoded data MD5 sum: %s\"",
"Creating decoded message...\" createdmessage = self.__createDecodedMessagePacket(decodedmessage) print \"Client: Sending decoded message...\" try: self.client.send(createdmessage.decode('hex'))",
"Hex: %s\" % (nm_length, hexnmlength) message_length = [hexnmlength[i:i+2] for i in range(0, len(hexnmlength),",
"ord(x) for x in md5sum ], [ x.encode('hex') for x in md5sum]) return",
"\"\\nNM decoded data MD5 sum: %s\" % md5sum nm_md5sum = [md5sum[i:i+2] for i"
] |
[
"subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True)",
"= models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order,",
"if order_max else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1",
"models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return",
"return order_max + 1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code =",
"from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1",
"def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\",",
") code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order =",
"{self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\",",
"= models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\":",
"models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\":",
"= models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering =",
") created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields",
"\"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\": lambda x: x.strftime(\"%Y-%m-%d\")}, {\"name\":",
"SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order",
"order_max + 1 if order_max else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return",
"= models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order,",
"created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields =",
"def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1",
"SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True)",
"+ 1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True)",
"models from django.db.models import Max from parler.models import TranslatableModel, TranslatedFields from utils.models import",
"def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda x:",
"= models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = (",
"= [\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory,",
"default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return self.code",
"return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")},",
"SortableMixin): code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order =",
"else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max",
"TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta:",
"unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True",
"get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 class",
"class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32,",
"on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}:",
"models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return",
"1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations",
"def __str__(self): return self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" )",
"translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True )",
"Meta: ordering = [\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin): profile = models.ForeignKey(",
"SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else",
"serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\":",
"get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 def",
"ordering = [\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey(",
"1 if order_max else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max +",
"enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\",",
"SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 def get_next_subscription_type_order(): order_max =",
"TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max +",
"__str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x,",
"order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel,",
"= models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" )",
"parler.models import TranslatableModel, TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"]",
"return self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type =",
"TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta:",
"f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\":",
"{\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\": lambda x: x.strftime(\"%Y-%m-%d\")},",
"created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering",
"Meta: ordering = [\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category =",
"= TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class",
"from adminsortable.models import SortableMixin from django.db import models from django.db.models import Max from",
"self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey(",
"return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code",
"SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code",
"SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations",
"db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin):",
"profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\"",
"django.db import models from django.db.models import Max from parler.models import TranslatableModel, TranslatedFields from",
"if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations =",
"[\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE,",
"adminsortable.models import SortableMixin from django.db import models from django.db.models import Max from parler.models",
"= TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class",
"order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 def get_next_subscription_type_order():",
"default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return self.code",
"\"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at =",
"related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\"",
"self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code =",
"order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def",
"[\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\"",
"SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at =",
"= models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255))",
"models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False,",
"on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True)",
"translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True )",
"from django.db.models import Max from parler.models import TranslatableModel, TranslatedFields from utils.models import SerializableMixin",
"order_max else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if",
"ordering = [\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\",",
"class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType,",
") subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled =",
"\"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\": lambda x: x.strftime(\"%Y-%m-%d\")}, {\"name\": \"enabled\"},",
"Max from parler.models import TranslatableModel, TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max",
"= models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering =",
"return order_max + 1 if order_max else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"]",
"Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE,",
"__str__(self): return self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type",
"def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1",
"SortableMixin from django.db import models from django.db.models import Max from parler.models import TranslatableModel,",
"import Max from parler.models import TranslatableModel, TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order():",
"created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering",
"models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at",
"models.BooleanField(default=True) def __str__(self): return f\"{self.subscription_type.code}: {self.enabled}\" serialize_fields = ( {\"name\": \"subscription_type\", \"accessor\": lambda",
"order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def",
"SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self): return",
"import TranslatableModel, TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return",
"class Meta: ordering = [\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin): profile =",
"from django.db import models from django.db.models import Max from parler.models import TranslatableModel, TranslatedFields",
"models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"]",
"code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField(",
"order_max + 1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32,",
"+ 1 if order_max else 1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max",
"( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\": lambda x:",
"from parler.models import TranslatableModel, TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max =",
"lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\": lambda x: x.strftime(\"%Y-%m-%d\")}, {\"name\": \"enabled\"}, )",
"import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max",
"on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True)",
"import models from django.db.models import Max from parler.models import TranslatableModel, TranslatedFields from utils.models",
"utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if",
"unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True",
"models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def __str__(self):",
") class Meta: ordering = [\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin):",
"<reponame>Sukriva/open-city-profile<filename>subscriptions/models.py from adminsortable.models import SortableMixin from django.db import models from django.db.models import Max",
"TranslatableModel, TranslatedFields from utils.models import SerializableMixin def get_next_subscription_type_category_order(): order_max = SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max",
"= models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self):",
"editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return self.code class",
"class Meta: ordering = [\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category",
"django.db.models import Max from parler.models import TranslatableModel, TranslatedFields from utils.models import SerializableMixin def",
"related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order",
"subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", ) code = models.CharField(max_length=32, unique=True) translations =",
"models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE, related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at",
"= ( {\"name\": \"subscription_type\", \"accessor\": lambda x: getattr(x, \"code\")}, {\"name\": \"created_at\", \"accessor\": lambda",
"1 def get_next_subscription_type_order(): order_max = SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else",
"= models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) def",
"import SortableMixin from django.db import models from django.db.models import Max from parler.models import",
"= models.PositiveIntegerField( default=get_next_subscription_type_category_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"] def __str__(self):",
"= [\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin): profile = models.ForeignKey( \"profiles.Profile\", on_delete=models.CASCADE,",
"order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255))",
"__str__(self): return self.code class SubscriptionType(TranslatableModel, SortableMixin): subscription_type_category = models.ForeignKey( SubscriptionTypeCategory, on_delete=models.CASCADE, related_name=\"subscription_types\", )",
"related_name=\"subscriptions\" ) subscription_type = models.ForeignKey( SubscriptionType, on_delete=models.CASCADE, related_name=\"subscriptions\" ) created_at = models.DateTimeField(auto_now_add=True) enabled",
"models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False,",
"1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at =",
"class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at = models.DateTimeField(auto_now_add=True)",
"models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField( default=get_next_subscription_type_order, editable=False, db_index=True ) class Meta: ordering = [\"order\"]",
"else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin): code = models.CharField(max_length=32, unique=True) translations = TranslatedFields(label=models.CharField(max_length=255)) created_at",
") class Meta: ordering = [\"order\"] def __str__(self): return self.code class Subscription(SerializableMixin): profile",
"= SubscriptionType.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 class SubscriptionTypeCategory(TranslatableModel, SortableMixin):",
"db_index=True ) class Meta: ordering = [\"order\"] def __str__(self): return self.code class SubscriptionType(TranslatableModel,",
"= SubscriptionTypeCategory.objects.aggregate(Max(\"order\"))[\"order__max\"] return order_max + 1 if order_max else 1 def get_next_subscription_type_order(): order_max"
] |
[
"kernels = np.transpose(kernels, (1, 0, 2, 3)) bias = bias.reshape(-1) current = _conv_layer(current,",
":] = curr_feat_vec for i in range(ntest): curr_feat = test_features[i, :, :, :]",
"of 'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\" %",
"Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) # Save",
"+ 1 # Divide total data into training and test set randidx =",
"enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] #",
"is %s\" % (testimg_tensor.shape,)) # Get conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\"",
"= imgcnt + 1 # Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3: return",
"3]) trainimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor is %s\"",
"# Convert to grayscale if use_gray: grayimg = rgb2gray(currimg) else: grayimg = currimg",
"imgcnt = 0 for i, relpath in zip(range(nclass), paths): path = cwd +",
"imgsize[0], imgsize[1], 3)) for i in range(ntrain): currimg = trainimg[i, :] currimg =",
"} biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input,",
"imread(fullpath) # Convert to grayscale if use_gray: grayimg = rgb2gray(currimg) else: grayimg =",
"np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :] = currimg print (\"Shape of",
"tf.Session() sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. num_batch",
"batches for i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :]",
"nclass = len(paths) for relpath in paths: fullpath = cwd + \"/\" +",
"-1)) # Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt",
"tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features =",
"for i in range(ntrain): curr_feat = train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat,",
"(train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\" Test accuracy:",
"flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(path, f) currimg =",
"skimage.io import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print",
"'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2',",
"dim n_output = nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024,",
"% (test_features.shape,)) # # 向量化 # In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512))",
"Divide total data into training and test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx",
"trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx,",
"(\"Package loaded\") print (\"Current folder is %s\" % (cwd) ) # In[2]: #",
"current = input_image for i, name in enumerate(layers): kind = name[:4] if kind",
"'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4',",
"img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder)",
"nclass]) keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input = dim n_output =",
"print (\" Training accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y:",
"'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel =",
"+ mean_pixel print (\"VGG net ready\") # # 使用VGG计算卷积特征图 # In[5]: # Preprocess",
"currimg = testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :,",
"2, 2, 1), padding='SAME') def preprocess(image, mean_pixel): return image - mean_pixel def unprocess(image,",
"y = tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input",
":] = grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1",
"# Return everything out = {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1,",
"else: grayimg = currimg # Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec =",
"= tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input):",
"np import os import scipy.io from scipy.misc import imread, imresize import matplotlib.pyplot as",
"# (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # #",
"= 0 for i, relpath in zip(range(nclass), paths): path = cwd + \"/\"",
"conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def",
"(1, -1)) train_vectorized[i, :] = curr_feat_vec for i in range(ntest): curr_feat = test_features[i,",
"inline') cwd = os.getcwd() print (\"Package loaded\") print (\"Current folder is %s\" %",
"[height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) bias =",
"imgsize[1], 3]) trainimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor is",
"'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',",
"strides=(1, 2, 2, 1), padding='SAME') def preprocess(image, mean_pixel): return image - mean_pixel def",
"%s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\" % (test_features.shape,)) # #",
"# # 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3))",
"= randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx,",
"# 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor",
"= nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))",
"= 10 # tf Graph input x = tf.placeholder(tf.float32, [None, 4*4*512]) y =",
"batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs,",
"numpy as np import os import scipy.io from scipy.misc import imread, imresize import",
"'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1',",
"\"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None,",
"(\"Shape of 'train_features' is %s\" % (train_features.shape,)) print (\"Shape of 'test_features' is %s\"",
"tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))",
"else: print (\"Current Image is GRAY!\") return rgb if use_gray: totalimg = np.ndarray((imgcnt,",
"Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt = imgcnt",
"bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1),",
"packs import numpy as np import os import scipy.io from scipy.misc import imread,",
"testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in range(ntrain): currimg = trainimg[i,",
"import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package loaded\") print",
"Configure the locations of the images and reshaping sizes # ------------------------------------------------------------------- # paths",
"imgsize = [64, 64] # The reshape size use_gray = 0 # Grayscale",
"nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of total",
"trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of total images is",
"currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :] = currimg print",
"i, relpath in zip(range(nclass), paths): path = cwd + \"/\" + relpath flist",
"net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2',",
"ntrain, ntest)) print (\"Shape of an image is (%d, %d, %d)\" % (imgsize[0],",
"_pool_layer(current) net[name] = current assert len(net) == len(layers) return net, mean_pixel def _conv_layer(input,",
"'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data =",
"= 100 display_step = 10 # tf Graph input x = tf.placeholder(tf.float32, [None,",
":] trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel = totallabel[testidx, :]",
"# 使用预训练的VGG模型Fine-tune CNN # In[1]: # Import packs import numpy as np import",
"scipy.io from scipy.misc import imread, imresize import matplotlib.pyplot as plt import skimage.io import",
"+ \"/\" + relpath flist = os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower()",
", shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder:",
":, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec for i",
"% (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 # In[4]: def net(data_path, input_image): layers",
"} def conv_basic(_input, _w, _b, _keepratio): # Input _input_r = _input # Vectorize",
"+ relpath flist = os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower() not in",
"size use_gray = 0 # Grayscale data_name = \"data4vgg\" # Save name valid_exts",
"paths = {\"images/cats\", \"images/dogs\"} imgsize = [64, 64] # The reshape size use_gray",
"features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"):",
"= int(ntrain/batch_size)+1 # Loop over all batches for i in range(num_batch): randidx =",
"# Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])",
"'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3',",
"stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def",
"= current assert len(net) == len(layers) return net, mean_pixel def _conv_layer(input, weights, bias):",
"3)) for i in range(ntrain): currimg = trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0],",
"Fit training using batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute",
"nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor})",
"Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0 nclass",
"tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME') def preprocess(image, mean_pixel):",
"mean_pixel print (\"VGG net ready\") # # 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor",
"= cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder =",
"向量化 # In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512))",
"are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) bias",
"y: batch_ys, keepratio:1.})/num_batch # Display logs per epoch step if epoch % display_step",
"everything out = {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out",
"# Grayscale data_name = \"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] #",
"for i in range(ntest): curr_feat = test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat,",
"0: print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr,",
"= 0 nclass = len(paths) for relpath in paths: fullpath = cwd +",
"randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx,",
"using batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss",
"avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs per epoch",
"i, name in enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias",
"_fc_dr1, 'out': _out } return out # Functions! _pred = conv_basic(x, weights, biases,",
"def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME')",
"% (test_features.shape,)) # # 定义finetuning的结构 # In[8]: # Parameters learning_rate = 0.0001 training_epochs",
"in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx,",
"totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt = imgcnt +",
"int(ntrain/batch_size)+1 # Loop over all batches for i in range(num_batch): randidx = np.random.randint(ntrain,",
"if use_gray: grayimg = rgb2gray(currimg) else: grayimg = currimg # Reshape graysmall =",
"= np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i",
"+ \"/\" + relpath flist = os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower()",
"in valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt = imgcnt + 1 #",
"valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt = imgcnt + 1 # Grayscale",
"coding: utf-8 # # 使用预训练的VGG模型Fine-tune CNN # In[1]: # Import packs import numpy",
"Return everything out = {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out':",
"locations of the images and reshaping sizes # ------------------------------------------------------------------- # paths = {\"images/cats\",",
"batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs per epoch step if epoch %",
"test_vectorized, y: testlabel, keepratio:1.}) print (\" Test accuracy: %.3f\" % (test_acc)) print (\"Optimization",
"for i in range(ntest): currimg = testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1],",
"'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2',",
"# coding: utf-8 # # 使用预训练的VGG模型Fine-tune CNN # In[1]: # Import packs import",
"matplotlib.pyplot as plt import skimage.io import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline')",
"# # 卷积特征图的形状 # In[6]: print (\"Shape of 'train_features' is %s\" % (train_features.shape,))",
"Launch the graph sess = tf.Session() sess.run(init) # Training cycle for epoch in",
"if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width,",
"net = {} current = input_image for i, name in enumerate(layers): kind =",
":] batch_ys = trainlabel[randidx, :] # Fit training using batch data sess.run(optm, feed_dict={x:",
"= tf.Session() sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0.",
"nclass)[i] imgcnt = imgcnt + 1 # Divide total data into training and",
"'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio): # Input _input_r =",
"import skimage.io import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd()",
"image + mean_pixel print (\"VGG net ready\") # # 使用VGG计算卷积特征图 # In[5]: #",
"is GRAY!\") return rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg =",
"net[name] = current assert len(net) == len(layers) return net, mean_pixel def _conv_layer(input, weights,",
"= testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :]",
"cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr =",
"# In[8]: # Parameters learning_rate = 0.0001 training_epochs = 100 batch_size = 100",
"print (\"Current folder is %s\" % (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 #",
"def unprocess(image, mean_pixel): return image + mean_pixel print (\"VGG net ready\") # #",
"batch_ys, keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys,",
"in valid_exts: continue fullpath = os.path.join(path, f) currimg = imread(fullpath) # Convert to",
"ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME') def preprocess(image, mean_pixel): return",
"_pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME') def",
"net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction",
"[width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels",
"of 'test_vectorized' is %s\" % (test_features.shape,)) # # 定义finetuning的结构 # In[8]: # Parameters",
"{} current = input_image for i, name in enumerate(layers): kind = name[:4] if",
"display_step = 10 # tf Graph input x = tf.placeholder(tf.float32, [None, 4*4*512]) y",
"_keepratio): # Input _input_r = _input # Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]])",
"(test_features.shape,)) # # 向量化 # In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized",
"tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3))",
"= tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready to Go!\") # #",
"(\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i in range(ntest): currimg =",
"(%d, %d, %d)\" % (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 # In[4]: def",
"totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0 for i, relpath in zip(range(nclass), paths):",
"range(ntest): curr_feat = test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i,",
"i in range(ntest): curr_feat = test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1,",
"nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) }",
"os.getcwd() print (\"Package loaded\") print (\"Current folder is %s\" % (cwd) ) #",
"%.9f\" % (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})",
"np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current Image is GRAY!\") return rgb if",
"print (\"Current Image is GRAY!\") return rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]))",
"current = _conv_layer(current, kernels, bias) elif kind == 'relu': current = tf.nn.relu(current) elif",
"imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0",
"(1, -1)) # Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i]",
"biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w,",
"Go!\") # # 优化 # In[9]: # Launch the graph sess = tf.Session()",
"as np import os import scipy.io from scipy.misc import imread, imresize import matplotlib.pyplot",
"for relpath in paths: fullpath = cwd + \"/\" + relpath flist =",
"stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2':",
"# Launch the graph sess = tf.Session() sess.run(init) # Training cycle for epoch",
"num_batch = int(ntrain/batch_size)+1 # Loop over all batches for i in range(num_batch): randidx",
"= ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1',",
"f) currimg = imread(fullpath) # Convert to grayscale if use_gray: grayimg = rgb2gray(currimg)",
"(imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 # In[4]: def net(data_path, input_image): layers =",
"in range(ntrain): currimg = trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i,",
"# Configure the locations of the images and reshaping sizes # ------------------------------------------------------------------- #",
"1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),",
"range(ntrain): currimg = trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :,",
"Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i in range(ntrain):",
"= tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features",
"tf.initialize_all_variables() print (\"Network Ready to Go!\") # # 优化 # In[9]: # Launch",
"sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\" Test accuracy: %.3f\" % (test_acc))",
":, :] = currimg print (\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,)) #",
"is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current Image is GRAY!\")",
"len(net) == len(layers) return net, mean_pixel def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input,",
"sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel",
"len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current Image is",
":] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec for i in",
"def preprocess(image, mean_pixel): return image - mean_pixel def unprocess(image, mean_pixel): return image +",
"imgsize[1], 3)) # # 定义VGG网络结构 # In[4]: def net(data_path, input_image): layers = (",
"in range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1 # Loop over all batches",
"graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt,",
"keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input = dim n_output = nclass",
"imgcnt + 1 # Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3],",
"data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations of the",
"kind == 'relu': current = tf.nn.relu(current) elif kind == 'pool': current = _pool_layer(current)",
"载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations of the images and reshaping sizes",
"cwd + \"/\" + relpath flist = os.listdir(path) for f in flist: if",
"2, 1), strides=(1, 2, 2, 1), padding='SAME') def preprocess(image, mean_pixel): return image -",
"np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net = {} current = input_image for",
"if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current Image",
"data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights =",
"np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat = train_features[i, :, :, :] curr_feat_vec",
"flist = os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue",
"with tf.device(\"/cpu:0\"): n_input = dim n_output = nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512,",
"{'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out",
"and test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt]",
"kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] #",
"total images is %d (train: %d, test: %d)\" % (imgcnt, ntrain, ntest)) print",
"init = tf.initialize_all_variables() print (\"Network Ready to Go!\") # # 优化 # In[9]:",
"extraction done\") # # 卷积特征图的形状 # In[6]: print (\"Shape of 'train_features' is %s\"",
"train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] # Fit training using batch data sess.run(optm,",
"use_gray: grayimg = rgb2gray(currimg) else: grayimg = currimg # Reshape graysmall = imresize(grayimg,",
"i in range(ntrain): currimg = trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3])",
"In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat",
"tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input = dim n_output = nclass weights =",
"# Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2",
"tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package loaded\") print (\"Current",
"(\" Training accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel,",
"= np.transpose(kernels, (1, 0, 2, 3)) bias = bias.reshape(-1) current = _conv_layer(current, kernels,",
"# Get conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as",
"range(ntrain): curr_feat = train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i,",
"trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") # # 卷积特征图的形状 #",
"test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec",
"tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out = {'input_r': _input_r, 'dense1': _dense1, 'fc1':",
"_b, _keepratio): # Input _input_r = _input # Vectorize _dense1 = tf.reshape(_input_r, [-1,",
"'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out # Functions! _pred =",
"'out': _out } return out # Functions! _pred = conv_basic(x, weights, biases, keepratio)['out']",
"定义VGG网络结构 # In[4]: def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2',",
"0 # Grayscale data_name = \"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"]",
"current = _pool_layer(current) net[name] = current assert len(net) == len(layers) return net, mean_pixel",
"np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0 for i, relpath in",
"(1, -1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape of 'train_vectorized' is %s\" %",
"currimg = imread(fullpath) # Convert to grayscale if use_gray: grayimg = rgb2gray(currimg) else:",
"imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt,",
"'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio): #",
"os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath =",
"data['layers'][0] net = {} current = input_image for i, name in enumerate(layers): kind",
"sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost,",
"display_step == 0: print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc",
"imgcnt = imgcnt + 1 # Divide total data into training and test",
"= totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain =",
"path = cwd + \"/\" + relpath flist = os.listdir(path) for f in",
"[imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :] = grayvec",
"= sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\" %",
"kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet:",
"tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready to Go!\") # # 优化",
"keepratio:1.}) print (\" Training accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized,",
"4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"):",
"else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0 for",
"imgsize[1], 3)) for i in range(ntrain): currimg = trainimg[i, :] currimg = np.reshape(currimg,",
"test: %d)\" % (imgcnt, ntrain, ntest)) print (\"Shape of an image is (%d,",
"tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready to Go!\") # # 优化 #",
"cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys,",
"= tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything",
"{\"images/cats\", \"images/dogs\"} imgsize = [64, 64] # The reshape size use_gray = 0",
"\".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0 nclass = len(paths) for relpath in",
"= np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] =",
"matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width,",
"Parameters learning_rate = 0.0001 training_epochs = 100 batch_size = 100 display_step = 10",
"'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2',",
"_b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) #",
"Import packs import numpy as np import os import scipy.io from scipy.misc import",
":] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :] = currimg",
"= sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\" Test accuracy: %.3f\" %",
"imgcnt = imgcnt + 1 # Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3:",
"# In[1]: # Import packs import numpy as np import os import scipy.io",
"grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1 # Divide",
"are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels]",
"_w, _b, _keepratio): # Input _input_r = _input # Vectorize _dense1 = tf.reshape(_input_r,",
"valid_exts: continue fullpath = os.path.join(path, f) currimg = imread(fullpath) # Convert to grayscale",
"= trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of total images is %d (train:",
"out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) bias = bias.reshape(-1) current =",
"# tensorflow: weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0,",
"mean_pixel): return image + mean_pixel print (\"VGG net ready\") # # 使用VGG计算卷积特征图 #",
"= totallabel[testidx, :] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest",
"1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1),",
"relpath flist = os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts:",
"_w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])",
"return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2,",
"trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for",
"print (\"Shape of 'test_vectorized' is %s\" % (test_features.shape,)) # # 定义finetuning的结构 # In[8]:",
"= tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out = {'input_r': _input_r, 'dense1': _dense1,",
"(注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集",
"# imgcnt = 0 nclass = len(paths) for relpath in paths: fullpath =",
"n_output = nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output],",
"bias = bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif kind == 'relu': current",
"logs per epoch step if epoch % display_step == 0: print (\"Epoch: %03d/%03d",
"'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3',",
"the locations of the images and reshaping sizes # ------------------------------------------------------------------- # paths =",
"imread, imresize import matplotlib.pyplot as plt import skimage.io import skimage.transform import tensorflow as",
"Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else:",
"%d)\" % (imgcnt, ntrain, ntest)) print (\"Shape of an image is (%d, %d,",
"currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :] = currimg print",
"Ready to Go!\") # # 优化 # In[9]: # Launch the graph sess",
"% (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\" Test",
"'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1',",
"= randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx, :]",
"= np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :] = currimg print (\"Shape",
"Image is GRAY!\") return rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg",
"= input_image for i, name in enumerate(layers): kind = name[:4] if kind ==",
"weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv,",
":, :, :] = currimg print (\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,))",
"# 卷积特征图的形状 # In[6]: print (\"Shape of 'train_features' is %s\" % (train_features.shape,)) print",
"# In[9]: # Launch the graph sess = tf.Session() sess.run(init) # Training cycle",
"'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2',",
"unprocess(image, mean_pixel): return image + mean_pixel print (\"VGG net ready\") # # 使用VGG计算卷积特征图",
"elif kind == 'relu': current = tf.nn.relu(current) elif kind == 'pool': current =",
"relpath in paths: fullpath = cwd + \"/\" + relpath flist = os.listdir(fullpath)",
"_fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out =",
"training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\" Training",
"plt import skimage.io import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd =",
"return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME') def preprocess(image,",
"is %s\" % (test_features.shape,)) # # 定义finetuning的结构 # In[8]: # Parameters learning_rate =",
"batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost",
"return rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3))",
"0 nclass = len(paths) for relpath in paths: fullpath = cwd + \"/\"",
"= np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0 for i, relpath",
"is %s\" % (trainimg_tensor.shape,)) for i in range(ntest): currimg = testimg[i, :] currimg",
"'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path)",
"sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs per epoch step if",
"def rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print",
"import imread, imresize import matplotlib.pyplot as plt import skimage.io import skimage.transform import tensorflow",
"train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec",
"(\"Number of total images is %d (train: %d, test: %d)\" % (imgcnt, ntrain,",
"fullpath = os.path.join(path, f) currimg = imread(fullpath) # Convert to grayscale if use_gray:",
"bias) elif kind == 'relu': current = tf.nn.relu(current) elif kind == 'pool': current",
"In[8]: # Parameters learning_rate = 0.0001 training_epochs = 100 batch_size = 100 display_step",
"stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio): # Input _input_r",
"sess = tf.Session() sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost =",
"feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\" % (train_acc)) test_acc",
"'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4'",
"def conv_basic(_input, _w, _b, _keepratio): # Input _input_r = _input # Vectorize _dense1",
"for i, relpath in zip(range(nclass), paths): path = cwd + \"/\" + relpath",
"(\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs,",
"= currimg print (\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get conv",
"-1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape of 'train_vectorized' is %s\" % (train_features.shape,))",
"print (\"Shape of an image is (%d, %d, %d)\" % (imgsize[0], imgsize[1], 3))",
"'fc_dr1': _fc_dr1, 'out': _out } return out # Functions! _pred = conv_basic(x, weights,",
"0.114]) else: print (\"Current Image is GRAY!\") return rgb if use_gray: totalimg =",
"imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in range(ntrain):",
"'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean =",
"get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package loaded\") print (\"Current folder is %s\"",
"curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec for i in range(ntest):",
"# Loop over all batches for i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size)",
"reshape size use_gray = 0 # Grayscale data_name = \"data4vgg\" # Save name",
"bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias)",
"os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath =",
"if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: #",
"grayscale if use_gray: grayimg = rgb2gray(currimg) else: grayimg = currimg # Reshape graysmall",
"np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :] = currimg print (\"Shape of",
"= nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") # #",
"curr_feat_vec for i in range(ntest): curr_feat = test_features[i, :, :, :] curr_feat_vec =",
"i in range(ntrain): curr_feat = train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1,",
"current assert len(net) == len(layers) return net, mean_pixel def _conv_layer(input, weights, bias): conv",
"下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') #",
"tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio): # Input",
"feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs per epoch step if epoch",
"print (\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get conv features VGG_PATH",
"net ready\") # # 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0],",
"= nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") # # 卷积特征图的形状 # In[6]: print",
"is %s\" % (train_features.shape,)) print (\"Shape of 'test_features' is %s\" % (test_features.shape,)) #",
"= data['layers'][0] net = {} current = input_image for i, name in enumerate(layers):",
"# 定义finetuning的结构 # In[8]: # Parameters learning_rate = 0.0001 training_epochs = 100 batch_size",
"# 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations of the images and reshaping",
"3)) bias = bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif kind == 'relu':",
"= currimg print (\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i in",
"print (\"VGG net ready\") # # 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor =",
"= trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :]",
"# In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for",
"# In[6]: print (\"Shape of 'train_features' is %s\" % (train_features.shape,)) print (\"Shape of",
"_b['bd2']) # Return everything out = {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1':",
"(1, 0, 2, 3)) bias = bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif",
"tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print",
"= _conv_layer(current, kernels, bias) elif kind == 'relu': current = tf.nn.relu(current) elif kind",
"'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data",
"Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3))",
"% (train_features.shape,)) print (\"Shape of 'test_features' is %s\" % (test_features.shape,)) # # 向量化",
"'train_features' is %s\" % (train_features.shape,)) print (\"Shape of 'test_features' is %s\" % (test_features.shape,))",
"np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in",
"totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0 for i,",
"# 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat')",
"cwd + \"/\" + relpath flist = os.listdir(fullpath) for f in flist: if",
"= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr,",
"trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of",
"current = tf.nn.relu(current) elif kind == 'pool': current = _pool_layer(current) net[name] = current",
"Get conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess:",
"in range(ntest): curr_feat = test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1))",
"'relu': current = tf.nn.relu(current) elif kind == 'pool': current = _pool_layer(current) net[name] =",
"step if epoch % display_step == 0: print (\"Epoch: %03d/%03d cost: %.9f\" %",
"%.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\"",
"feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x:",
"= test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] =",
"1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2,",
"np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape of 'train_vectorized' is %s\"",
"# Training cycle for epoch in range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1",
"if epoch % display_step == 0: print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch,",
"Convert to grayscale if use_gray: grayimg = rgb2gray(currimg) else: grayimg = currimg #",
"http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations of the images",
"In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0],",
"'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\" % (test_features.shape,))",
"= net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map",
"_fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out # Functions! _pred = conv_basic(x,",
"% (imgcnt, ntrain, ntest)) print (\"Shape of an image is (%d, %d, %d)\"",
"使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor =",
"%s\" % (test_features.shape,)) # # 定义finetuning的结构 # In[8]: # Parameters learning_rate = 0.0001",
"over all batches for i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs =",
"_corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network",
"totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0]",
"------------------------------------------------------------------- # imgcnt = 0 nclass = len(paths) for relpath in paths: fullpath",
"continue fullpath = os.path.join(fullpath, f) imgcnt = imgcnt + 1 # Grayscale def",
"size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel =",
"to Go!\") # # 优化 # In[9]: # Launch the graph sess =",
"tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input,",
"(train: %d, test: %d)\" % (imgcnt, ntrain, ntest)) print (\"Shape of an image",
"os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the",
"_conv_layer(current, kernels, bias) elif kind == 'relu': current = tf.nn.relu(current) elif kind ==",
"== 'relu': current = tf.nn.relu(current) elif kind == 'pool': current = _pool_layer(current) net[name]",
"in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) bias = bias.reshape(-1) current",
"conv_basic(_input, _w, _b, _keepratio): # Input _input_r = _input # Vectorize _dense1 =",
"# 优化 # In[9]: # Launch the graph sess = tf.Session() sess.run(init) #",
"'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3',",
"testimg = totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0] nclass =",
"cycle for epoch in range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1 # Loop",
":] testimg = totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0] nclass",
"% display_step == 0: print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost))",
":, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec for",
"_input # Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1,",
"import matplotlib.pyplot as plt import skimage.io import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib",
"mean_pixel): return image - mean_pixel def unprocess(image, mean_pixel): return image + mean_pixel print",
"as plt import skimage.io import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd",
"== len(layers) return net, mean_pixel def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights),",
"# In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest,",
"trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :] =",
"if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(path, f) currimg = imread(fullpath)",
"size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] # Fit training using",
"10 # tf Graph input x = tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32,",
"= tf.initialize_all_variables() print (\"Network Ready to Go!\") # # 优化 # In[9]: #",
"y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y:",
"folder is %s\" % (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import",
"= data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net = {}",
"out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1,",
"utf-8 # # 使用预训练的VGG模型Fine-tune CNN # In[1]: # Import packs import numpy as",
"mean_pixel def unprocess(image, mean_pixel): return image + mean_pixel print (\"VGG net ready\") #",
"= curr_feat_vec for i in range(ntest): curr_feat = test_features[i, :, :, :] curr_feat_vec",
"= os.getcwd() print (\"Package loaded\") print (\"Current folder is %s\" % (cwd) )",
"import skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package",
"y: batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr,",
"# # 使用预训练的VGG模型Fine-tune CNN # In[1]: # Import packs import numpy as np",
"( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1',",
"batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x:",
"valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0 nclass = len(paths)",
"input_image for i, name in enumerate(layers): kind = name[:4] if kind == 'conv':",
"weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are",
"Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out = {'input_r': _input_r,",
"graph sess = tf.Session() sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost",
"the images and reshaping sizes # ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize",
"if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel =",
"name in enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias =",
"print (\"Shape of 'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized' is",
"data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net = {} current",
"images and reshaping sizes # ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize =",
"axis=(0, 1)) weights = data['layers'][0] net = {} current = input_image for i,",
"net, mean_pixel def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1,",
"= 0 # Grayscale data_name = \"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\",",
"mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional",
"(epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\"",
"'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4',",
"Display logs per epoch step if epoch % display_step == 0: print (\"Epoch:",
"batch_xs, y: batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\" % (train_acc)) test_acc =",
"'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1))",
"# Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1],",
"os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt = imgcnt +",
"randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] #",
"import scipy.io from scipy.misc import imread, imresize import matplotlib.pyplot as plt import skimage.io",
"imgcnt = 0 nclass = len(paths) for relpath in paths: fullpath = cwd",
"%d, test: %d)\" % (imgcnt, ntrain, ntest)) print (\"Shape of an image is",
"= np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1 # Divide total data into",
"in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(path, f) currimg",
"padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1,",
"curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape of 'train_vectorized'",
"% (train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\" % (test_features.shape,)) # # 定义finetuning的结构",
"bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow:",
"tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH,",
"定义finetuning的结构 # In[8]: # Parameters learning_rate = 0.0001 training_epochs = 100 batch_size =",
"accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready to Go!\") #",
"= trainlabel[randidx, :] # Fit training using batch data sess.run(optm, feed_dict={x: batch_xs, y:",
"0.587, 0.114]) else: print (\"Current Image is GRAY!\") return rgb if use_gray: totalimg",
"print (\"Network Ready to Go!\") # # 优化 # In[9]: # Launch the",
"curr_feat = test_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :]",
"= os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath",
"for epoch in range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1 # Loop over",
"= dim n_output = nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2':",
"for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(fullpath,",
"= curr_feat_vec print (\"Shape of 'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape of",
"= tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) #",
"mean_pixel def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1),",
"1 # Divide total data into training and test set randidx = np.random.randint(imgcnt,",
"from scipy.misc import imread, imresize import matplotlib.pyplot as plt import skimage.io import skimage.transform",
"imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt = 0 for i, relpath in zip(range(nclass),",
"= name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights",
"tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready to Go!\")",
"== 0: print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc =",
"\"images/dogs\"} imgsize = [64, 64] # The reshape size use_gray = 0 #",
":] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0]",
"is %d (train: %d, test: %d)\" % (imgcnt, ntrain, ntest)) print (\"Shape of",
"'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel",
"tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return",
"= cwd + \"/\" + relpath flist = os.listdir(fullpath) for f in flist:",
"labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init",
"train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\"",
"{ 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = {",
"totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1 # Divide total",
"= grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1 #",
"= tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 =",
"%d)\" % (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 # In[4]: def net(data_path, input_image):",
"return image - mean_pixel def unprocess(image, mean_pixel): return image + mean_pixel print (\"VGG",
":, :, :] = currimg print (\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,))",
"fullpath = os.path.join(fullpath, f) imgcnt = imgcnt + 1 # Grayscale def rgb2gray(rgb):",
"not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure",
"== 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels,",
"np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat = train_features[i,",
"+ 1 # Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299,",
"testimg.shape[0] print (\"Number of total images is %d (train: %d, test: %d)\" %",
"learning_rate = 0.0001 training_epochs = 100 batch_size = 100 display_step = 10 #",
"the graph sess = tf.Session() sess.run(init) # Training cycle for epoch in range(training_epochs):",
"# In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O",
"# Display logs per epoch step if epoch % display_step == 0: print",
"# ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize = [64, 64] # The",
"imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :] =",
":] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :] = currimg",
"4*4*512)) for i in range(ntrain): curr_feat = train_features[i, :, :, :] curr_feat_vec =",
"# # 优化 # In[9]: # Launch the graph sess = tf.Session() sess.run(init)",
"np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] = np.eye(nclass,",
"Training accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.})",
"'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',",
"with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel =",
"weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3))",
"if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt = imgcnt",
"'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean",
"keepratio:0.7}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch",
"3)) # # 定义VGG网络结构 # In[4]: def net(data_path, input_image): layers = ( 'conv1_1',",
"= tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready",
"data_name = \"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- #",
"testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg =",
"kind == 'pool': current = _pool_layer(current) net[name] = current assert len(net) == len(layers)",
"n_output], stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) }",
"'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0]",
"def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME')",
"epoch % display_step == 0: print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs,",
"y: testlabel, keepratio:1.}) print (\" Test accuracy: %.3f\" % (test_acc)) print (\"Optimization Finished!\")",
"loaded\") print (\"Current folder is %s\" % (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取",
"currimg = trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :,",
"'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2',",
"imgsize[1], 3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in range(ntrain): currimg",
"} return out # Functions! _pred = conv_basic(x, weights, biases, keepratio)['out'] cost =",
"os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(path, f) currimg = imread(fullpath) #",
"# Import packs import numpy as np import os import scipy.io from scipy.misc",
"(train_features.shape,)) print (\"Shape of 'test_features' is %s\" % (test_features.shape,)) # # 向量化 #",
"batch_size = 100 display_step = 10 # tf Graph input x = tf.placeholder(tf.float32,",
"0. num_batch = int(ntrain/batch_size)+1 # Loop over all batches for i in range(num_batch):",
"_w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) #",
"'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',",
"is (%d, %d, %d)\" % (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 # In[4]:",
"cwd = os.getcwd() print (\"Package loaded\") print (\"Current folder is %s\" % (cwd)",
"# # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations of the images and",
"testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :] =",
"= 0.0001 training_epochs = 100 batch_size = 100 display_step = 10 # tf",
"epoch in range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1 # Loop over all",
"in enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0]",
"tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio): # Input _input_r = _input",
"# Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out = {'input_r':",
"tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out",
"trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i in range(ntest): currimg = testimg[i, :]",
"in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels,",
"loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs per",
"reshaping sizes # ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize = [64, 64]",
"= tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1,",
"# Parameters learning_rate = 0.0001 training_epochs = 100 batch_size = 100 display_step =",
"%s\" % (trainimg_tensor.shape,)) for i in range(ntest): currimg = testimg[i, :] currimg =",
"test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\" Test accuracy: %.3f\"",
"np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] # Fit training",
":] testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim =",
"print (\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i in range(ntest): currimg",
"i in range(ntest): currimg = testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3])",
"randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx, :]",
"is %s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\" % (test_features.shape,)) #",
"trainimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor is %s\" %",
"image - mean_pixel def unprocess(image, mean_pixel): return image + mean_pixel print (\"VGG net",
"64] # The reshape size use_gray = 0 # Grayscale data_name = \"data4vgg\"",
"'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out # Functions!",
"= imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :]",
"accuracy: %.3f\" % (train_acc)) test_acc = sess.run(accr, feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print",
"% (testimg_tensor.shape,)) # Get conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(),",
"os.path.join(path, f) currimg = imread(fullpath) # Convert to grayscale if use_gray: grayimg =",
"%s\" % (train_features.shape,)) print (\"Shape of 'test_features' is %s\" % (test_features.shape,)) # #",
"= train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] # Fit training using batch data",
"'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4',",
"100 batch_size = 100 display_step = 10 # tf Graph input x =",
"f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(path, f)",
"_dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1",
"[None, nclass]) keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input = dim n_output",
"(\"Shape of 'test_vectorized' is %s\" % (test_features.shape,)) # # 定义finetuning的结构 # In[8]: #",
"优化 # In[9]: # Launch the graph sess = tf.Session() sess.run(init) # Training",
"to grayscale if use_gray: grayimg = rgb2gray(currimg) else: grayimg = currimg # Reshape",
"(\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get conv features VGG_PATH =",
"return image + mean_pixel print (\"VGG net ready\") # # 使用VGG计算卷积特征图 # In[5]:",
"= _pool_layer(current) net[name] = current assert len(net) == len(layers) return net, mean_pixel def",
"# Network with tf.device(\"/cpu:0\"): n_input = dim n_output = nclass weights = {",
"Loop over all batches for i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs",
"paths: fullpath = cwd + \"/\" + relpath flist = os.listdir(fullpath) for f",
"= cwd + \"/\" + relpath flist = os.listdir(path) for f in flist:",
"randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg",
"(\"Shape of 'test_features' is %s\" % (test_features.shape,)) # # 向量化 # In[7]: #",
"Grayscale data_name = \"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # -------------------------------------------------------------------",
"tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32))",
"'pool': current = _pool_layer(current) net[name] = current assert len(net) == len(layers) return net,",
"-1)) train_vectorized[i, :] = curr_feat_vec for i in range(ntest): curr_feat = test_features[i, :,",
"'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0,",
"dim = trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of total images is %d",
"n_input = dim n_output = nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)),",
"'test_vectorized' is %s\" % (test_features.shape,)) # # 定义finetuning的结构 # In[8]: # Parameters learning_rate",
"return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current Image is GRAY!\") return rgb",
"elif kind == 'pool': current = _pool_layer(current) net[name] = current assert len(net) ==",
":, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec print",
"of an image is (%d, %d, %d)\" % (imgsize[0], imgsize[1], 3)) # #",
"%s\" % (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if",
"'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1',",
"VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder",
"= np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :]",
"(train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\" % (test_features.shape,)) # # 定义finetuning的结构 #",
"\"/\" + relpath flist = os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower() not",
"- mean_pixel def unprocess(image, mean_pixel): return image + mean_pixel print (\"VGG net ready\")",
"'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' )",
"np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1 # Divide total data into training",
"_fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return",
"mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net = {} current =",
"for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(path,",
"os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]:",
"weights = data['layers'][0] net = {} current = input_image for i, name in",
"'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bd1':",
"# Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :] = np.eye(nclass, nclass)[i] imgcnt =",
"3]) testimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor is %s\"",
"bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif kind == 'relu': current = tf.nn.relu(current)",
"= currimg # Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1,",
"-O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations of",
"batch_ys = trainlabel[randidx, :] # Fit training using batch data sess.run(optm, feed_dict={x: batch_xs,",
"os import scipy.io from scipy.misc import imread, imresize import matplotlib.pyplot as plt import",
"= { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases =",
"tf Graph input x = tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass])",
"in zip(range(nclass), paths): path = cwd + \"/\" + relpath flist = os.listdir(path)",
"(\"Network Ready to Go!\") # # 优化 # In[9]: # Launch the graph",
"print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x:",
"map extraction done\") # # 卷积特征图的形状 # In[6]: print (\"Shape of 'train_features' is",
"Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out",
"= conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr",
"trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get conv features VGG_PATH = cwd +",
":] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape of",
"of 'train_features' is %s\" % (train_features.shape,)) print (\"Shape of 'test_features' is %s\" %",
"= scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0]",
"_input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out #",
"layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',",
"conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr =",
"= imread(fullpath) # Convert to grayscale if use_gray: grayimg = rgb2gray(currimg) else: grayimg",
"imgcnt + 1 # Divide total data into training and test set randidx",
"= {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return",
"i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys =",
"# Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch #",
"tf.nn.relu(current) elif kind == 'pool': current = _pool_layer(current) net[name] = current assert len(net)",
"% (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print",
"kernels, bias) elif kind == 'relu': current = tf.nn.relu(current) elif kind == 'pool':",
"print (\"Number of total images is %d (train: %d, test: %d)\" % (imgcnt,",
"totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim",
"= np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :] = currimg print (\"Shape",
"with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0],",
"2, 2, 1), strides=(1, 2, 2, 1), padding='SAME') def preprocess(image, mean_pixel): return image",
"rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current",
"biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1))",
"3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder:",
"= testimg.shape[0] print (\"Number of total images is %d (train: %d, test: %d)\"",
") # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget",
"in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt",
"# In[3]: # Configure the locations of the images and reshaping sizes #",
"0, 2, 3)) bias = bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif kind",
"stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio): # Input _input_r = _input #",
"'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',",
"input x = tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio =",
":] # Fit training using batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})",
"keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr",
"skimage.transform import tensorflow as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package loaded\")",
"as tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package loaded\") print (\"Current folder",
"not in valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt = imgcnt + 1",
"= 0. num_batch = int(ntrain/batch_size)+1 # Loop over all batches for i in",
"# 向量化 # In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest,",
"out # Functions! _pred = conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y))",
"of total images is %d (train: %d, test: %d)\" % (imgcnt, ntrain, ntest))",
"# Divide total data into training and test set randidx = np.random.randint(imgcnt, size=imgcnt)",
"and reshaping sizes # ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize = [64,",
"in range(ntrain): curr_feat = train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1))",
"images is %d (train: %d, test: %d)\" % (imgcnt, ntrain, ntest)) print (\"Shape",
"CNN # In[1]: # Import packs import numpy as np import os import",
"# # 向量化 # In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized =",
"is %s\" % (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path",
"scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net",
"------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize = [64, 64] # The reshape",
"_conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return",
"relpath flist = os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts:",
"in range(ntest): currimg = testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i,",
"= weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights",
"% (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not",
"all batches for i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx,",
":, :] = currimg print (\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for",
"currimg print (\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get conv features",
"for i, name in enumerate(layers): kind = name[:4] if kind == 'conv': kernels,",
"imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features =",
"fullpath = cwd + \"/\" + relpath flist = os.listdir(fullpath) for f in",
"sizes # ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"} imgsize = [64, 64] #",
"currimg # Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1))",
"ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0] print",
"%03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y:",
"[-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio)",
"# paths = {\"images/cats\", \"images/dogs\"} imgsize = [64, 64] # The reshape size",
"= os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath",
"nclass)) imgcnt = 0 for i, relpath in zip(range(nclass), paths): path = cwd",
"3: return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) else: print (\"Current Image is GRAY!\") return",
"batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] # Fit training using batch",
"per epoch step if epoch % display_step == 0: print (\"Epoch: %03d/%03d cost:",
"imresize import matplotlib.pyplot as plt import skimage.io import skimage.transform import tensorflow as tf",
"image is (%d, %d, %d)\" % (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 #",
"1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2,",
"(test_features.shape,)) # # 定义finetuning的结构 # In[8]: # Parameters learning_rate = 0.0001 training_epochs =",
"'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels]",
"out = {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out }",
"train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") #",
"nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") # # 卷积特征图的形状 # In[6]: print (\"Shape",
"= len(paths) for relpath in paths: fullpath = cwd + \"/\" + relpath",
"= trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of total images",
":, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape",
"training using batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average",
"conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with",
"f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(fullpath, f)",
"an image is (%d, %d, %d)\" % (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构",
"test_vectorized = np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat = train_features[i, :, :,",
"range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :]",
"= imgcnt + 1 # Divide total data into training and test set",
"[0.299, 0.587, 0.114]) else: print (\"Current Image is GRAY!\") return rgb if use_gray:",
"get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 # In[3]: # Configure the locations",
"print (\"Shape of 'test_features' is %s\" % (test_features.shape,)) # # 向量化 # In[7]:",
"import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'): get_ipython().system(u'wget -O data/imagenet-vgg-verydeep-19.mat http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat') # # 载入图像,调节尺寸,生成数据集 #",
"zip(range(nclass), paths): path = cwd + \"/\" + relpath flist = os.listdir(path) for",
"2, 1), padding='SAME') def preprocess(image, mean_pixel): return image - mean_pixel def unprocess(image, mean_pixel):",
"# tf Graph input x = tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None,",
"f) imgcnt = imgcnt + 1 # Grayscale def rgb2gray(rgb): if len(rgb.shape) is",
"testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1]",
"return net, mean_pixel def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1,",
"(\"Current folder is %s\" % (cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同)",
"np.ndarray((imgcnt, nclass)) imgcnt = 0 for i, relpath in zip(range(nclass), paths): path =",
"tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2,",
"training_epochs = 100 batch_size = 100 display_step = 10 # tf Graph input",
"average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs",
"_pred = conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)",
"tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1,",
"return out # Functions! _pred = conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred,",
"os.path.join(fullpath, f) imgcnt = imgcnt + 1 # Grayscale def rgb2gray(rgb): if len(rgb.shape)",
"= train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] =",
"%s\" % (testimg_tensor.shape,)) # Get conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with",
"ntest)) print (\"Shape of an image is (%d, %d, %d)\" % (imgsize[0], imgsize[1],",
"feed_dict={x: test_vectorized, y: testlabel, keepratio:1.}) print (\" Test accuracy: %.3f\" % (test_acc)) print",
"# In[4]: def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',",
"len(layers) return net, mean_pixel def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1,",
"= tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input = dim n_output = nclass weights",
"of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i in range(ntest): currimg = testimg[i,",
"# Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall, (1, -1)) #",
"= {\"images/cats\", \"images/dogs\"} imgsize = [64, 64] # The reshape size use_gray =",
"ntest = testimg.shape[0] print (\"Number of total images is %d (train: %d, test:",
":] = curr_feat_vec print (\"Shape of 'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape",
"Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))",
"np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec for i in range(ntest): curr_feat =",
"'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4',",
"= np.reshape(curr_feat, (1, -1)) test_vectorized[i, :] = curr_feat_vec print (\"Shape of 'train_vectorized' is",
"testimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor is %s\" %",
"0 for i, relpath in zip(range(nclass), paths): path = cwd + \"/\" +",
"grayimg = currimg # Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec = np.reshape(graysmall,",
"In[7]: # Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i",
"sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. num_batch =",
"assert len(net) == len(layers) return net, mean_pixel def _conv_layer(input, weights, bias): conv =",
"relpath in zip(range(nclass), paths): path = cwd + \"/\" + relpath flist =",
"np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt =",
"= tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables()",
"= rgb2gray(currimg) else: grayimg = currimg # Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255.",
"weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases",
"% (trainimg_tensor.shape,)) for i in range(ntest): currimg = testimg[i, :] currimg = np.reshape(currimg,",
"imgsize[1], 3]) testimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor is",
"flist = os.listdir(path) for f in flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue",
"tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']),",
"_input_r = _input # Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1",
"= totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel =",
":] = currimg print (\"Shape of trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get",
"imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features",
"100 display_step = 10 # tf Graph input x = tf.placeholder(tf.float32, [None, 4*4*512])",
"# Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']),",
"_dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out # Functions! _pred",
"shape=(None, imgsize[0], imgsize[1], 3)) nets, mean_pixel = net(VGG_PATH, img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor})",
"tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1],",
"In[6]: print (\"Shape of 'train_features' is %s\" % (train_features.shape,)) print (\"Shape of 'test_features'",
"= np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net = {} current = input_image",
"_keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out =",
"= _input # Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 =",
"+ \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 ,",
"train_vectorized[i, :] = curr_feat_vec for i in range(ntest): curr_feat = test_features[i, :, :,",
"batch_ys, keepratio:1.})/num_batch # Display logs per epoch step if epoch % display_step ==",
"range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1 # Loop over all batches for",
"'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2',",
"= os.path.join(fullpath, f) imgcnt = imgcnt + 1 # Grayscale def rgb2gray(rgb): if",
"optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init =",
"width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) bias = bias.reshape(-1)",
"data into training and test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)]",
"1), strides=(1, 2, 2, 1), padding='SAME') def preprocess(image, mean_pixel): return image - mean_pixel",
"in paths: fullpath = cwd + \"/\" + relpath flist = os.listdir(fullpath) for",
"+ relpath flist = os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower() not in",
"# # 定义finetuning的结构 # In[8]: # Parameters learning_rate = 0.0001 training_epochs = 100",
"= [64, 64] # The reshape size use_gray = 0 # Grayscale data_name",
"2, 3)) bias = bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif kind ==",
"print (\"Package loaded\") print (\"Current folder is %s\" % (cwd) ) # In[2]:",
"import numpy as np import os import scipy.io from scipy.misc import imread, imresize",
"is %s\" % (test_features.shape,)) # # 向量化 # In[7]: # Vectorize train_vectorized =",
"+= sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display logs per epoch step",
"(testimg_tensor.shape,)) # Get conv features VGG_PATH = cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session()",
"%d (train: %d, test: %d)\" % (imgcnt, ntrain, ntest)) print (\"Shape of an",
"training and test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx =",
"[imgsize[0], imgsize[1], 3]) testimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor",
"'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean,",
"(trainimg_tensor.shape,)) for i in range(ntest): currimg = testimg[i, :] currimg = np.reshape(currimg, [imgsize[0],",
"_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out = {'input_r': _input_r, 'dense1':",
"name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are",
"{ 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b, _keepratio):",
"In[9]: # Launch the graph sess = tf.Session() sess.run(init) # Training cycle for",
"print(\"Convolutional map extraction done\") # # 卷积特征图的形状 # In[6]: print (\"Shape of 'train_features'",
":] = np.eye(nclass, nclass)[i] imgcnt = imgcnt + 1 # Divide total data",
"test_vectorized[i, :] = curr_feat_vec print (\"Shape of 'train_vectorized' is %s\" % (train_features.shape,)) print",
"curr_feat_vec print (\"Shape of 'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized'",
"test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg",
"3)) testimg_tensor = np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in range(ntrain): currimg =",
"use_gray = 0 # Grayscale data_name = \"data4vgg\" # Save name valid_exts =",
"totallabel[testidx, :] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest =",
"curr_feat = train_features[i, :, :, :] curr_feat_vec = np.reshape(curr_feat, (1, -1)) train_vectorized[i, :]",
") data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights",
"of 'test_features' is %s\" % (test_features.shape,)) # # 向量化 # In[7]: # Vectorize",
"(imgcnt, ntrain, ntest)) print (\"Shape of an image is (%d, %d, %d)\" %",
"np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg = totalimg[trainidx, :] trainlabel",
"= np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys = trainlabel[randidx, :] # Fit",
"totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass))",
"rgb2gray(currimg) else: grayimg = currimg # Reshape graysmall = imresize(grayimg, [imgsize[0], imgsize[1]])/255. grayvec",
"'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1',",
"Network with tf.device(\"/cpu:0\"): n_input = dim n_output = nclass weights = { 'wd1':",
"height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels =",
"Training cycle for epoch in range(training_epochs): avg_cost = 0. num_batch = int(ntrain/batch_size)+1 #",
"'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output],",
"trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain",
"Graph input x = tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio",
"use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt,",
"of trainimg_tensor is %s\" % (testimg_tensor.shape,)) # Get conv features VGG_PATH = cwd",
"of the images and reshaping sizes # ------------------------------------------------------------------- # paths = {\"images/cats\", \"images/dogs\"}",
"x = tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32)",
"(\"VGG net ready\") # # 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain,",
"卷积特征图的形状 # In[6]: print (\"Shape of 'train_features' is %s\" % (train_features.shape,)) print (\"Shape",
"into training and test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx",
"len(paths) for relpath in paths: fullpath = cwd + \"/\" + relpath flist",
"The reshape size use_gray = 0 # Grayscale data_name = \"data4vgg\" # Save",
"= np.ndarray((imgcnt, nclass)) imgcnt = 0 for i, relpath in zip(range(nclass), paths): path",
"= tf.nn.relu(current) elif kind == 'pool': current = _pool_layer(current) net[name] = current assert",
"avg_cost = 0. num_batch = int(ntrain/batch_size)+1 # Loop over all batches for i",
"1)) weights = data['layers'][0] net = {} current = input_image for i, name",
"0.0001 training_epochs = 100 batch_size = 100 display_step = 10 # tf Graph",
"weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels,",
"%s\" % (test_features.shape,)) # # 向量化 # In[7]: # Vectorize train_vectorized = np.ndarray((ntrain,",
"currimg print (\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i in range(ntest):",
"print (\"Shape of 'train_features' is %s\" % (train_features.shape,)) print (\"Shape of 'test_features' is",
"In[3]: # Configure the locations of the images and reshaping sizes # -------------------------------------------------------------------",
"epoch step if epoch % display_step == 0: print (\"Epoch: %03d/%03d cost: %.9f\"",
"trainimg.shape[1] ntest = testimg.shape[0] print (\"Number of total images is %d (train: %d,",
"# matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height,",
"# The reshape size use_gray = 0 # Grayscale data_name = \"data4vgg\" #",
"tf.placeholder(tf.float32, [None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) # Network",
"In[1]: # Import packs import numpy as np import os import scipy.io from",
"= np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel = np.ndarray((imgcnt, nclass)) imgcnt",
"name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0 nclass =",
"1 # Grayscale def rgb2gray(rgb): if len(rgb.shape) is 3: return np.dot(rgb[...,:3], [0.299, 0.587,",
"= [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0 nclass = len(paths) for",
"(cwd) ) # In[2]: # 下载预先训练好的vgg-19模型,为Matlab的.mat格式,之后会用scipy读取 # (注意此版本模型与此处http://www.vlfeat.org/matconvnet/pretrained/最新版本不同) import os.path if not os.path.isfile('./data/imagenet-vgg-verydeep-19.mat'):",
"'test_features' is %s\" % (test_features.shape,)) # # 向量化 # In[7]: # Vectorize train_vectorized",
"# Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0",
"done\") # # 卷积特征图的形状 # In[6]: print (\"Shape of 'train_features' is %s\" %",
"= \"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt",
"# Fit training using batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) #",
"trainimg = totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel",
"range(ntest): currimg = testimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1], 3]) testimg_tensor[i, :,",
"# Vectorize train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i in",
"# Functions! _pred = conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm",
"[None, 4*4*512]) y = tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) # Network with",
"train_vectorized = np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat",
"tensorflow: weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2,",
"\"/\" + relpath flist = os.listdir(fullpath) for f in flist: if os.path.splitext(f)[1].lower() not",
"nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") # # 卷积特征图的形状",
"= np.ndarray((ntrain, 4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat =",
"(\"Shape of 'train_vectorized' is %s\" % (train_features.shape,)) print (\"Shape of 'test_vectorized' is %s\"",
"= 100 batch_size = 100 display_step = 10 # tf Graph input x",
"mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net =",
"GRAY!\") return rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt,",
"trainlabel[randidx, :] # Fit training using batch data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys,",
"'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',",
"paths): path = cwd + \"/\" + relpath flist = os.listdir(path) for f",
"[64, 64] # The reshape size use_gray = 0 # Grayscale data_name =",
"tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input = dim",
"# 定义VGG网络结构 # In[4]: def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2',",
"continue fullpath = os.path.join(path, f) currimg = imread(fullpath) # Convert to grayscale if",
"[imgsize[0], imgsize[1], 3]) trainimg_tensor[i, :, :, :] = currimg print (\"Shape of trainimg_tensor",
"img_placeholder) train_features = nets['relu5_4'].eval(feed_dict={img_placeholder: trainimg_tensor}) test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\")",
"(\"Current Image is GRAY!\") return rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else:",
"# Input _input_r = _input # Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) #",
"\"data4vgg\" # Save name valid_exts = [\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt =",
"== 'pool': current = _pool_layer(current) net[name] = current assert len(net) == len(layers) return",
"tf get_ipython().magic(u'matplotlib inline') cwd = os.getcwd() print (\"Package loaded\") print (\"Current folder is",
"weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) _corr = tf.equal(tf.argmax(_pred,1),",
"testimg_tensor}) print(\"Convolutional map extraction done\") # # 卷积特征图的形状 # In[6]: print (\"Shape of",
"keepratio:1.})/num_batch # Display logs per epoch step if epoch % display_step == 0:",
"Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/num_batch # Display",
"4*4*512)) test_vectorized = np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat = train_features[i, :,",
"input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2',",
"grayvec = np.reshape(graysmall, (1, -1)) # Save totalimg[imgcnt, :] = grayvec totallabel[imgcnt, :]",
"Functions! _pred = conv_basic(x, weights, biases, keepratio)['out'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y)) optm =",
"not in valid_exts: continue fullpath = os.path.join(path, f) currimg = imread(fullpath) # Convert",
"= np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in range(ntrain): currimg = trainimg[i, :]",
"preprocess(image, mean_pixel): return image - mean_pixel def unprocess(image, mean_pixel): return image + mean_pixel",
"In[4]: def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1',",
"= np.reshape(curr_feat, (1, -1)) train_vectorized[i, :] = curr_feat_vec for i in range(ntest): curr_feat",
"total data into training and test set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx =",
"= tf.placeholder(tf.float32, [None, nclass]) keepratio = tf.placeholder(tf.float32) # Network with tf.device(\"/cpu:0\"): n_input =",
"# # 定义VGG网络结构 # In[4]: def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1',",
"kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height,",
"as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32 , shape=(None, imgsize[0], imgsize[1], 3)) nets,",
"set randidx = np.random.randint(imgcnt, size=imgcnt) trainidx = randidx[0:int(4*imgcnt/5)] testidx = randidx[int(4*imgcnt/5):imgcnt] trainimg =",
"# ------------------------------------------------------------------- # imgcnt = 0 nclass = len(paths) for relpath in paths:",
"'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4',",
"cwd + \"/data/imagenet-vgg-verydeep-19.mat\" with tf.Graph().as_default(), tf.Session() as sess: with tf.device(\"/cpu:0\"): img_placeholder = tf.placeholder(tf.float32",
"= bias.reshape(-1) current = _conv_layer(current, kernels, bias) elif kind == 'relu': current =",
"使用预训练的VGG模型Fine-tune CNN # In[1]: # Import packs import numpy as np import os",
"[\".jpg\",\".gif\",\".png\",\".tga\", \".jpeg\"] # ------------------------------------------------------------------- # imgcnt = 0 nclass = len(paths) for relpath",
"rgb if use_gray: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1])) else: totalimg = np.ndarray((imgcnt, imgsize[0]*imgsize[1]*3)) totallabel",
"flist: if os.path.splitext(f)[1].lower() not in valid_exts: continue fullpath = os.path.join(fullpath, f) imgcnt =",
"= {} current = input_image for i, name in enumerate(layers): kind = name[:4]",
"np.transpose(kernels, (1, 0, 2, 3)) bias = bias.reshape(-1) current = _conv_layer(current, kernels, bias)",
"strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1,",
"totalimg[trainidx, :] trainlabel = totallabel[trainidx, :] testimg = totalimg[testidx, :] testlabel = totallabel[testidx,",
"grayimg = rgb2gray(currimg) else: grayimg = currimg # Reshape graysmall = imresize(grayimg, [imgsize[0],",
"data sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7}) # Compute average loss avg_cost +=",
"scipy.misc import imread, imresize import matplotlib.pyplot as plt import skimage.io import skimage.transform import",
"avg_cost)) train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\" Training accuracy:",
"def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1',",
"(\"Shape of an image is (%d, %d, %d)\" % (imgsize[0], imgsize[1], 3)) #",
"tf.Variable(tf.random_normal([4*4*512, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bd1': tf.Variable(tf.random_normal([1024],",
"ready\") # # 使用VGG计算卷积特征图 # In[5]: # Preprocess trainimg_tensor = np.ndarray((ntrain, imgsize[0], imgsize[1],",
"%d, %d)\" % (imgsize[0], imgsize[1], 3)) # # 定义VGG网络结构 # In[4]: def net(data_path,",
"_w['wd2']), _b['bd2']) # Return everything out = {'input_r': _input_r, 'dense1': _dense1, 'fc1': _fc1,",
"tf.equal(tf.argmax(_pred,1), tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(_corr, tf.float32)) init = tf.initialize_all_variables() print (\"Network Ready to",
"= np.ndarray((ntest, 4*4*512)) for i in range(ntrain): curr_feat = train_features[i, :, :, :]",
"= totalimg[testidx, :] testlabel = totallabel[testidx, :] ntrain = trainimg.shape[0] nclass = trainlabel.shape[1]",
"Input _input_r = _input # Vectorize _dense1 = tf.reshape(_input_r, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1",
"1), padding='SAME') def preprocess(image, mean_pixel): return image - mean_pixel def unprocess(image, mean_pixel): return",
"= trainimg.shape[0] nclass = trainlabel.shape[1] dim = trainimg.shape[1] ntest = testimg.shape[0] print (\"Number",
"_out } return out # Functions! _pred = conv_basic(x, weights, biases, keepratio)['out'] cost",
"= os.path.join(path, f) currimg = imread(fullpath) # Convert to grayscale if use_gray: grayimg",
"sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.}) print (\" Training accuracy: %.3f\" % (train_acc))",
"np.ndarray((ntest, imgsize[0], imgsize[1], 3)) for i in range(ntrain): currimg = trainimg[i, :] currimg",
"padding='SAME') def preprocess(image, mean_pixel): return image - mean_pixel def unprocess(image, mean_pixel): return image",
"test_features = nets['relu5_4'].eval(feed_dict={img_placeholder: testimg_tensor}) print(\"Convolutional map extraction done\") # # 卷积特征图的形状 # In[6]:",
":] = currimg print (\"Shape of trainimg_tensor is %s\" % (trainimg_tensor.shape,)) for i",
"import os import scipy.io from scipy.misc import imread, imresize import matplotlib.pyplot as plt",
"= { 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } def conv_basic(_input, _w, _b,",
"tf.device(\"/cpu:0\"): n_input = dim n_output = nclass weights = { 'wd1': tf.Variable(tf.random_normal([4*4*512, 1024],",
"for i in range(num_batch): randidx = np.random.randint(ntrain, size=batch_size) batch_xs = train_vectorized[randidx, :] batch_ys",
"for i in range(ntrain): currimg = trainimg[i, :] currimg = np.reshape(currimg, [imgsize[0], imgsize[1],"
] |
[
"[ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object",
"a key/value JSON object file in an S3 bucket through the CLI\", author_email=\"<EMAIL>\",",
"through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT', install_requires=requires, entry_points=''' [console_scripts] s3env=s3env:cli ''', )",
"setuptools import setup requires = [ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\",",
"S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT', install_requires=requires, entry_points=''' [console_scripts] s3env=s3env:cli",
"in an S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT', install_requires=requires, entry_points='''",
"'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object file in",
"JSON object file in an S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'],",
"'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object file",
"] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object file in an",
"file in an S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT', install_requires=requires,",
"setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object file in an S3",
"name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object file in an S3 bucket",
"= [ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON",
"requires = [ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value",
"an S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT', install_requires=requires, entry_points=''' [console_scripts]",
"setup requires = [ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a",
"author=\"<NAME>\", description=\"Manipulate a key/value JSON object file in an S3 bucket through the",
"description=\"Manipulate a key/value JSON object file in an S3 bucket through the CLI\",",
"object file in an S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT',",
"version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate a key/value JSON object file in an S3 bucket through",
"import setup requires = [ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\", author=\"<NAME>\", description=\"Manipulate",
"bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env', py_modules=['s3env'], license='MIT', install_requires=requires, entry_points=''' [console_scripts] s3env=s3env:cli ''',",
"key/value JSON object file in an S3 bucket through the CLI\", author_email=\"<EMAIL>\", url='https://github.com/cameronmaske/s3env',",
"from setuptools import setup requires = [ 'click==6.7', 'bucketstore==0.1.1' ] setup( name=\"s3env\", version=\"0.0.4\","
] |
[
"= str(input('Insira o valor hora (HH:MM): ')).split(':') min = int(hora[1]) min += int(hora[0])",
"hora (HH:MM): ')).split(':') min = int(hora[1]) min += int(hora[0]) * 60 print(f'Passaram-se {min}",
"#Ex.11 hora = str(input('Insira o valor hora (HH:MM): ')).split(':') min = int(hora[1]) min",
"')).split(':') min = int(hora[1]) min += int(hora[0]) * 60 print(f'Passaram-se {min} minutos desde",
"o valor hora (HH:MM): ')).split(':') min = int(hora[1]) min += int(hora[0]) * 60",
"min = int(hora[1]) min += int(hora[0]) * 60 print(f'Passaram-se {min} minutos desde as",
"(HH:MM): ')).split(':') min = int(hora[1]) min += int(hora[0]) * 60 print(f'Passaram-se {min} minutos",
"= int(hora[1]) min += int(hora[0]) * 60 print(f'Passaram-se {min} minutos desde as 00:00h.')",
"str(input('Insira o valor hora (HH:MM): ')).split(':') min = int(hora[1]) min += int(hora[0]) *",
"hora = str(input('Insira o valor hora (HH:MM): ')).split(':') min = int(hora[1]) min +=",
"valor hora (HH:MM): ')).split(':') min = int(hora[1]) min += int(hora[0]) * 60 print(f'Passaram-se",
"<gh_stars>1-10 #Ex.11 hora = str(input('Insira o valor hora (HH:MM): ')).split(':') min = int(hora[1])"
] |
[
"to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict match using a user-defined",
"'assertion') for idx, entry in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def dict_ns():",
"can be equal if they refer to the same numeric value - in",
"in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with a",
"assert dict_ns.match( actual, expected, description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self,",
"from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils import comparison,",
"result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with a mocked out result object.\"\"\" mock_result",
"mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace",
"= dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Discard ignored comparisons',",
"result): summary = result.subresult() first = result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True,",
"by seting different types that can be compared. Due to duck-typing, ints and",
"@testsuite class AssertionOrder(object): @testcase def case(self, env, result): summary = result.subresult() first =",
"= mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with",
"FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for FIX match.\"\"\" expected",
"entry for entry in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] == 'assertion') for",
"{'key': 123} actual = expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch of identical",
"string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the match method",
"== 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected,",
"default') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert",
"match \"123\". \"\"\" expected = {'key': 123} actual = {'key': '123'} assert not",
"to ' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test",
"match') # Now change the type of the actual 38 key's value to",
"description='Dictmatch fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected,",
"a dict match using a user-defined comparison function.\"\"\" expected = {'key': 174.24} actual",
"= fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Keep ignored comparisons',",
"assert dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED)",
"types that can be compared. Due to duck-typing, ints and floats can be",
"expected, description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert",
"def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed FIX messages.\"\"\" expected = testing.FixMessage(",
"value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the match method for types that do",
"actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not fix_ns.match( actual,",
"passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1",
"'1000000' assert not fix_ns.match( actual, expected, description='Failing str/int comparison') # Change the type",
"i in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert =",
"tolerance assert not dict_ns.match( actual, expected, description='Values are not exactly equal') assert dict_ns.match(",
"def case(self, env, result): summary = result.subresult() first = result.subresult() second = result.subresult()",
"type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values to strings before",
"comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict match using",
"the numeric values are equal.') assert not dict_ns.match( actual, expected, description='Dictmatch fails when",
"comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch with string conversion",
"actual, expected, description='Keep all comparisons by default') assert len(dict_ns.result.entries) == 1 dict_assert =",
"equal.') assert not dict_ns.match( actual, expected, description='Dictmatch fails when type comparison is forced.',",
"assert len(dict_assert.comparison) == 3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons')",
"'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.')",
"match method for types that do not compare equal - in this case,",
"123 == 123.0. However if type-checking is forced by use of the check_types",
"\"\"\"Test controlling report modes for a dict match.\"\"\" expected = {'key{}'.format(i): i for",
"are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for",
"1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Discard",
"= testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual = expected.copy() assert",
"assert fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes",
"passes when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a",
"def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for FIX match.\"\"\" expected = testing.FixMessage((i,",
"Due to duck-typing, ints and floats can be equal if they refer to",
"description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped FIX messages.\"\"\" expected =",
"be compared. Due to duck-typing, ints and floats can be equal if they",
"However if type-checking is forced by use of the check_types comparison method the",
"if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected =",
"by default') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11",
"comparison, testing @testsuite class AssertionOrder(object): @testcase def case(self, env, result): summary = result.subresult()",
"description='Dictmatch fails because 123 != \"123') assert not dict_ns.match( actual, expected, description='Dictmatch fails",
"description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed FIX messages.\"\"\"",
"comparisons') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class",
"assert dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert",
"== 11 assert dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in",
"testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected,",
"match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed FIX messages.\"\"\" expected =",
"numeric value - in this case, 123 == 123.0. However if type-checking is",
"expected = testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual = expected.copy()",
"assert fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries)",
"38 key's value to str. The assert # should fail since we are",
"len(dict_assert.comparison) == 3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert",
"Test the match method against identical expected and actual dicts. \"\"\" expected =",
"- rhs) < tolerance assert not dict_ns.match( actual, expected, description='Values are not exactly",
"\"\"\"Test controlling report modes for FIX match.\"\"\" expected = testing.FixMessage((i, (25 * i)",
"result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond',",
"are equal.') assert not dict_ns.match( actual, expected, description='Dictmatch fails when type comparison is",
"mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report",
"TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the",
"len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not dict_ns.match(",
"the type of the actual 38 key's value to str. The assert #",
"'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.') if first.passed: summary.append(second) result.prepend(summary)",
"FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual",
"mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class",
"Now change the type of the actual 38 key's value to str. The",
"actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft()",
"the actual 38 key's value to str. The assert # should fail since",
"test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed FIX messages.\"\"\" expected = testing.FixMessage( ((35,",
"{'key{}'.format(i): i for i in range(10)} actual = expected.copy() expected['wrong'] = 'expected' actual['wrong']",
"result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\"",
"not dict_ns.match( actual, expected, description='Values are not exactly equal') assert dict_ns.match( actual, expected,",
"\"\"\" Test the match method by seting different types that can be compared.",
"< tolerance assert not dict_ns.match( actual, expected, description='Values are not exactly equal') assert",
"11 assert dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)])",
"representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the match method for",
"first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.') if first.passed: summary.append(second) result.prepend(summary) def",
"controlling report modes for a dict match.\"\"\" expected = {'key{}'.format(i): i for i",
"mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace",
"= dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Keep ignored comparisons',",
"'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed",
"if type-checking is forced by use of the check_types comparison method the assertion",
"entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with a mocked out result",
"difference, despite the numeric values being equal. actual[38] = 1000000.0 assert not fix_ns.match(",
"description='Keep all comparisons by default') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert",
"FIX matches between typed FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, 1000000),",
"dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases for the",
"actual['wrong'] = 'actual' assert not fix_ns.match( actual, expected, description='Keep all comparisons by default')",
"to str. The assert # should fail since we are performing a typed",
"testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils import comparison, testing",
"assertions = ( entry for entry in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type']",
"that both values are within a given tolerance range.\"\"\" return abs(lhs - rhs)",
"actual, expected, description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1",
"dict_ns(): \"\"\"Dict namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries",
"entry['meta_type'] == 'assertion') for idx, entry in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture",
"(38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self,",
"comparison method the assertion will fail. \"\"\" expected = {'key': 123} actual =",
"case(self, env, result): summary = result.subresult() first = result.subresult() second = result.subresult() second.true(True,",
"\"\"\" expected = {'key': 123} actual = {'key': 123.0} assert dict_ns.match( actual, expected,",
"assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not",
"actual = {'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both",
"not dict_ns.match( actual, expected, description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match(",
"values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the match",
"mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with a",
"mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] #",
"object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX",
"len(dict_assert.comparison) == 3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert",
"value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for a dict match.\"\"\" expected",
"\"123') assert not dict_ns.match( actual, expected, description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types'])",
"between untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')))",
"values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify'])",
"result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns():",
"collections import mock import pytest from testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite",
"AssertionOrder(object): @testcase def case(self, env, result): summary = result.subresult() first = result.subresult() second",
"( entry for entry in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] == 'assertion')",
"{'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes since the numeric values are",
"= MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed",
"fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for",
"'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] # pylint: disable=invalid-sequence-index assertions =",
"assert fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between",
"1 class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test",
"comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the match method by seting different",
"expected, description='Basic dictmatch of identical dicts passes') assert dict_ns.match( actual, expected, description='Force type-check",
"dict match using a user-defined comparison function.\"\"\" expected = {'key': 174.24} actual =",
"expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) ==",
"values are within a given tolerance range.\"\"\" return abs(lhs - rhs) < tolerance",
"by use of the check_types comparison method the assertion will fail. \"\"\" expected",
"values are equal.') assert not dict_ns.match( actual, expected, description='Dictmatch fails when type comparison",
"def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are within a given tolerance range.\"\"\"",
"given tolerance range.\"\"\" return abs(lhs - rhs) < tolerance assert not dict_ns.match( actual,",
"duck-typing, ints and floats can be equal if they refer to the same",
"passes since the numeric values are equal.') assert not dict_ns.match( actual, expected, description='Dictmatch",
"not dict_ns.match( actual, expected, description='Keep all comparisons by default') assert len(dict_ns.result.entries) == 1",
"to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes when values are",
"expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage(",
"for FIX match.\"\"\" expected = testing.FixMessage((i, (25 * i) - 4) for i",
"(38, 1000000), (44, 125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX",
"the same numeric value - in this case, 123 == 123.0. However if",
"= ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] # pylint: disable=invalid-sequence-index",
"FIX matches between typed and untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'),",
"actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries)",
"tests for the testplan.testing.multitest.result module.\"\"\" import collections import mock import pytest from testplan.testing.multitest",
"import result as result_mod from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import MultiTest",
"typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') # Now change",
"since we are performing a typed match. actual[38] = '1000000' assert not fix_ns.match(",
"actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed",
"untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False)",
"'1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self, fix_ns):",
"= ( entry for entry in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] ==",
"using a user-defined comparison function.\"\"\" expected = {'key': 174.24} actual = {'key': 174.87}",
"summary.append(first) result.true(first.passed, 'Report passed so far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest",
"dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY,",
"1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Discard",
"expected, description='Basic FIX match') # Now change the type of the actual 38",
"assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match(",
"report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"= collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with a mocked out",
"assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1",
"dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY,",
"1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are within a given tolerance",
"= {'key': 174.24} actual = {'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs):",
"value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict match using a user-defined comparison function.\"\"\"",
"with a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return",
"modes for a dict match.\"\"\" expected = {'key{}'.format(i): i for i in range(10)}",
"change the type of the actual 38 key's value to str. The assert",
"= testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed",
"= expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not dict_ns.match( actual, expected,",
"is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch with string conversion fails",
"to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the match method",
"converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict match using a",
"entry in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with",
"messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83'))) actual = expected.copy()",
"((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38,",
"dictmatch of identical dicts passes') assert dict_ns.match( actual, expected, description='Force type-check of values',",
"{'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are",
"description='Values are not exactly equal') assert dict_ns.match( actual, expected, description='Values are equal within",
"11 assert fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert",
"test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for FIX match.\"\"\" expected = testing.FixMessage((i, (25",
"far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected",
"cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are within a given tolerance range.\"\"\" return",
"expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not dict_ns.match( actual, expected, description='Keep",
"messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual =",
"include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"11 assert dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)],",
"out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object):",
"'expected' actual['wrong'] = 'actual' assert not fix_ns.match( actual, expected, description='Keep all comparisons by",
"'125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert",
"to a float. The match should still fail because of # the type",
"fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1",
"method for types that do not compare equal - in this case, 123",
"disable=invalid-sequence-index assertions = ( entry for entry in mtest.report.flatten() if isinstance(entry, dict) and",
"test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35,",
"= expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX",
"(44, 125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') #",
"assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def",
"# Change the type to a float. The match should still fail because",
"key's value to str. The assert # should fail since we are performing",
"= result.subresult() first = result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True,",
"from testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object): @testcase def case(self, env, result):",
"typed and untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44,",
"dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i)",
"and untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')),",
"testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'),",
"import pytest from testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite import testcase, testsuite",
"len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i",
"i in range(10)} actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert",
"fail since we are performing a typed match. actual[38] = '1000000' assert not",
"assert not dict_ns.match( actual, expected, description='Dictmatch fails because 123 != \"123') assert not",
"equal. actual[38] = 1000000.0 assert not fix_ns.match( actual, expected, description='Failing float/int comparison') def",
"abs(lhs - rhs) < tolerance assert not dict_ns.match( actual, expected, description='Values are not",
"!= \"123') assert not dict_ns.match( actual, expected, description='Dictmatch fails due to type mismatch',",
"- in this case, 123 == 123.0. However if type-checking is forced by",
"== expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with a mocked out result object.\"\"\"",
"= testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual,",
"(25 * i) - 4) for i in range(10)) actual = expected.copy() expected['wrong']",
"when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch with",
"expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] # pylint:",
"125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling",
"= result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1')",
"description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert =",
"TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches",
"\"\"\" expected = {'key': 123} actual = {'key': '123'} assert not dict_ns.match( actual,",
"import mock import pytest from testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite import",
"\"\"\"FIX namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries =",
"this case, 123 == 123.0. However if type-checking is forced by use of",
"passes') assert dict_ns.match( actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual,",
"Test the match method by seting different types that can be compared. Due",
"match.\"\"\" expected = {'key{}'.format(i): i for i in range(10)} actual = expected.copy() expected['wrong']",
"len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0, 1, 2],",
"match method against identical expected and actual dicts. \"\"\" expected = {'key': 123}",
"dict_ns): \"\"\" Test the match method for types that do not compare equal",
"return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with a mocked out result object.\"\"\"",
"for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped FIX",
"== 'assertion') for idx, entry in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def",
"for a dict match.\"\"\" expected = {'key{}'.format(i): i for i in range(10)} actual",
"typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual,",
"type of the actual 38 key's value to str. The assert # should",
"to duck-typing, ints and floats can be equal if they refer to the",
"len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0, 1, 2])",
"int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the match method for types that",
"not match \"123\". \"\"\" expected = {'key': 123} actual = {'key': '123'} assert",
"description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft()",
"report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert",
"def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped FIX messages.\"\"\" expected = testing.FixMessage(",
"value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the match method by seting different types",
"= testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35,",
"range(10)) actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not fix_ns.match(",
"assert not fix_ns.match( actual, expected, description='Keep all comparisons by default') assert len(fix_ns.result.entries) ==",
"fails because 123 != \"123') assert not dict_ns.match( actual, expected, description='Dictmatch fails due",
"by default') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11",
"out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def",
"when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict",
"not dict_ns.match( actual, expected, description='Dictmatch fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert",
"can be compared. Due to duck-typing, ints and floats can be equal if",
"description='Basic dictmatch of identical dicts passes') assert dict_ns.match( actual, expected, description='Force type-check of",
"i) - 4) for i in range(10)) actual = expected.copy() expected['wrong'] = 'expected'",
"between typed and untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'),",
"from testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest",
"first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.') if first.passed: summary.append(second)",
"1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not dict_ns.match( actual, expected,",
"# should fail since we are performing a typed match. actual[38] = '1000000'",
"actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values",
"a user-defined comparison function.\"\"\" expected = {'key': 174.24} actual = {'key': 174.87} tolerance",
"dict_ns.match( actual, expected, description='Dictmatch passes when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def",
"\"\"\"Test FIX matches between untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38,",
"fix_ns): \"\"\"Test FIX matches between typed FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'),",
"suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.']",
"actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft()",
"compare equal - in this case, 123 should not match \"123\". \"\"\" expected",
"type to a float. The match should still fail because of # the",
"1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Keep",
"11 assert fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries)",
"with string conversion fails due to ' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify'])",
"float. The match should still fail because of # the type difference, despite",
"== 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected,",
"FIX match.\"\"\" expected = testing.FixMessage((i, (25 * i) - 4) for i in",
"since the numeric values are equal.') assert not dict_ns.match( actual, expected, description='Dictmatch fails",
"match should still fail because of # the type difference, despite the numeric",
"rhs) < tolerance assert not dict_ns.match( actual, expected, description='Values are not exactly equal')",
"= '1000000' assert not fix_ns.match( actual, expected, description='Failing str/int comparison') # Change the",
"different types that can be compared. Due to duck-typing, ints and floats can",
"include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft()",
"'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match') def",
"\"\"\" Test the match method against identical expected and actual dicts. \"\"\" expected",
"dicts passes') assert dict_ns.match( actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match(",
"case, 123 == 123.0. However if type-checking is forced by use of the",
"tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for a dict match.\"\"\"",
"type-checking is forced by use of the check_types comparison method the assertion will",
"# pylint: disable=invalid-sequence-index assertions = ( entry for entry in mtest.report.flatten() if isinstance(entry,",
"assert dict_ns.match( actual, expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns):",
"test_duck_match(self, dict_ns): \"\"\" Test the match method by seting different types that can",
"dict_ns.match( actual, expected, description='Dictmatch with string conversion fails due to ' 'different string",
"expected, description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for FIX",
"expected, description='Dictmatch fails because 123 != \"123') assert not dict_ns.match( actual, expected, description='Dictmatch",
"The match should still fail because of # the type difference, despite the",
"controlling report modes for FIX match.\"\"\" expected = testing.FixMessage((i, (25 * i) -",
"actual, expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling",
"test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for a dict match.\"\"\" expected = {'key{}'.format(i):",
"first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1',",
"174.24} actual = {'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that",
"expected, description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test",
"messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual =",
"# Now change the type of the actual 38 key's value to str.",
"mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with a mocked",
"summary = result.subresult() first = result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1')",
"the numeric values being equal. actual[38] = 1000000.0 assert not fix_ns.match( actual, expected,",
"as result_mod from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils",
"actual, expected, description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert",
"actual[38] = 1000000.0 assert not fix_ns.match( actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self,",
"assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0, 1,",
"\"\"\"Test a dict match using a user-defined comparison function.\"\"\" expected = {'key': 174.24}",
"far.'] # pylint: disable=invalid-sequence-index assertions = ( entry for entry in mtest.report.flatten() if",
"test_basic_match(self, dict_ns): \"\"\" Test the match method against identical expected and actual dicts.",
"compared. Due to duck-typing, ints and floats can be equal if they refer",
"user-defined comparison function.\"\"\" expected = {'key': 174.24} actual = {'key': 174.87} tolerance =",
"assert len(dict_assert.comparison) == 3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons')",
"= fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Discard ignored comparisons',",
"collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture def fix_ns(): \"\"\"FIX namespace with a mocked out result",
"for the testplan.testing.multitest.result module.\"\"\" import collections import mock import pytest from testplan.testing.multitest import",
"the match method by seting different types that can be compared. Due to",
"= 'expected' actual['wrong'] = 'actual' assert not fix_ns.match( actual, expected, description='Keep all comparisons",
"123} actual = {'key': '123'} assert not dict_ns.match( actual, expected, description='Dictmatch fails because",
"assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not",
"# the type difference, despite the numeric values being equal. actual[38] = 1000000.0",
"in this case, 123 should not match \"123\". \"\"\" expected = {'key': 123}",
"actual, expected, description='Dictmatch passes since the numeric values are equal.') assert not dict_ns.match(",
"Change the type to a float. The match should still fail because of",
"= 'expected' actual['wrong'] = 'actual' assert not dict_ns.match( actual, expected, description='Keep all comparisons",
"type difference, despite the numeric values being equal. actual[38] = 1000000.0 assert not",
"result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the match method against identical expected",
"match method by seting different types that can be compared. Due to duck-typing,",
"expected = {'key': 123} actual = expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch",
"untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83'))) actual",
"in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] == 'assertion') for idx, entry in",
"numeric values being equal. actual[38] = 1000000.0 assert not fix_ns.match( actual, expected, description='Failing",
"= expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch of identical dicts passes') assert",
"def test_basic_match(self, dict_ns): \"\"\" Test the match method against identical expected and actual",
"actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not dict_ns.match( actual,",
"for i in range(10)) actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual'",
"* i) - 4) for i in range(10)) actual = expected.copy() expected['wrong'] =",
"i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"str/int comparison') # Change the type to a float. The match should still",
"'123'} assert not dict_ns.match( actual, expected, description='Dictmatch fails because 123 != \"123') assert",
"not fix_ns.match( actual, expected, description='Keep all comparisons by default') assert len(fix_ns.result.entries) == 1",
"fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing",
"description='Basic FIX match') # Now change the type of the actual 38 key's",
"expected = {'key': 123} actual = {'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch",
"(44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self,",
"the type to a float. The match should still fail because of #",
"description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert",
"that do not compare equal - in this case, 123 should not match",
"len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self,",
"the testplan.testing.multitest.result module.\"\"\" import collections import mock import pytest from testplan.testing.multitest import result",
"== 11 assert fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED)",
"{'key': 123} actual = {'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes since",
"not fix_ns.match( actual, expected, description='Failing str/int comparison') # Change the type to a",
"method by seting different types that can be compared. Due to duck-typing, ints",
"fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes when",
"description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the",
"1000000), (44, 125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match')",
"dict) and entry['meta_type'] == 'assertion') for idx, entry in enumerate(assertions): assert entry['description'] ==",
"equal if they refer to the same numeric value - in this case,",
"a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result)",
"expected = {'key': 174.24} actual = {'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs,",
"description='Dictmatch passes since the numeric values are equal.') assert not dict_ns.match( actual, expected,",
"expected, description='Keep all comparisons by default') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft()",
"type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch with string",
"fix_ns.match( actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between",
"1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases for",
"method the assertion will fail. \"\"\" expected = {'key': 123} actual = {'key':",
"123 should not match \"123\". \"\"\" expected = {'key': 123} actual = {'key':",
"expected, description='Dictmatch fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual,",
"dict_ns.match( actual, expected, description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual,",
"dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Discard ignored",
"'1000000'), (44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') def",
"\"\"\"Dict namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries =",
"fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) ==",
"include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert",
"expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values to",
"of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the match method for types",
"actual[38] = '1000000' assert not fix_ns.match( actual, expected, description='Failing str/int comparison') # Change",
"matches between typed FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, 1000000), (44,",
"testing.FixMessage((i, (25 * i) - 4) for i in range(10)) actual = expected.copy()",
"for types that do not compare equal - in this case, 123 should",
"3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) ==",
"assert not dict_ns.match( actual, expected, description='Keep all comparisons by default') assert len(dict_ns.result.entries) ==",
"both values are within a given tolerance range.\"\"\" return abs(lhs - rhs) <",
"'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders():",
"expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83'))) actual = expected.copy() assert",
"identical dicts passes') assert dict_ns.match( actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert",
"= dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard",
"typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report",
"dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Keep ignored",
"comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed and untyped FIX messages.\"\"\"",
"is forced by use of the check_types comparison method the assertion will fail.",
"result as result_mod from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import MultiTest from",
"= dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace",
"values being equal. actual[38] = 1000000.0 assert not fix_ns.match( actual, expected, description='Failing float/int",
"'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] # pylint: disable=invalid-sequence-index assertions = (",
"dict_ns): \"\"\"Test controlling report modes for a dict match.\"\"\" expected = {'key{}'.format(i): i",
"comparisons by default') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual,",
"equal - in this case, 123 should not match \"123\". \"\"\" expected =",
"dict_ns.match( actual, expected, description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns):",
"the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped FIX messages.\"\"\"",
"= {'key{}'.format(i): i for i in range(10)} actual = expected.copy() expected['wrong'] = 'expected'",
"dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Discard ignored",
"mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\"",
"identical expected and actual dicts. \"\"\" expected = {'key': 123} actual = expected.copy()",
"= 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are within a given",
"dict_ns.match( actual, expected, description='Values are not exactly equal') assert dict_ns.match( actual, expected, description='Values",
"dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing",
"matches between typed and untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38,",
"in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"== 3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries)",
"'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] # pylint: disable=invalid-sequence-index assertions = ( entry",
"are not exactly equal') assert dict_ns.match( actual, expected, description='Values are equal within tolerance',",
"= expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not fix_ns.match( actual, expected,",
"fix_ns): \"\"\"Test FIX matches between untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'),",
"in range(10)} actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not",
"ignored comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft()",
"all comparisons by default') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"expected, description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert =",
"assert entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with a mocked out",
"the check_types comparison method the assertion will fail. \"\"\" expected = {'key': 123}",
"'actual' assert not dict_ns.match( actual, expected, description='Keep all comparisons by default') assert len(dict_ns.result.entries)",
"1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Keep",
"dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i)",
"the assertion will fail. \"\"\" expected = {'key': 123} actual = {'key': 123.0}",
"expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') # Now change the type of",
"object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases",
"and actual dicts. \"\"\" expected = {'key': 123} actual = expected.copy() assert dict_ns.match(",
"result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed,",
"are within a given tolerance range.\"\"\" return abs(lhs - rhs) < tolerance assert",
"match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for FIX match.\"\"\" expected =",
"being equal. actual[38] = 1000000.0 assert not fix_ns.match( actual, expected, description='Failing float/int comparison')",
"summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2',",
"\"123\". \"\"\" expected = {'key': 123} actual = {'key': '123'} assert not dict_ns.match(",
"= 'actual' assert not fix_ns.match( actual, expected, description='Keep all comparisons by default') assert",
"assert not fix_ns.match( actual, expected, description='Failing str/int comparison') # Change the type to",
"FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed FIX messages.\"\"\" expected",
"len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not fix_ns.match(",
"dict_ns.match( actual, expected, description='Dictmatch fails because 123 != \"123') assert not dict_ns.match( actual,",
"passed so far.'] # pylint: disable=invalid-sequence-index assertions = ( entry for entry in",
"strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict match using a user-defined comparison",
"actual['wrong'] = 'actual' assert not dict_ns.match( actual, expected, description='Keep all comparisons by default')",
"= mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the",
"report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object):",
"be equal if they refer to the same numeric value - in this",
"the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the match method against identical",
"fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Discard ignored comparisons', include_tags=[0,",
"result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit",
"equal') assert dict_ns.match( actual, expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self,",
"all comparisons by default') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert =",
"comparisons by default') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"a float. The match should still fail because of # the type difference,",
"3 assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) ==",
"def test_duck_match(self, dict_ns): \"\"\" Test the match method by seting different types that",
"result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True,",
"this case, 123 should not match \"123\". \"\"\" expected = {'key': 123} actual",
"actual, expected, description='Failing str/int comparison') # Change the type to a float. The",
"dict_ns): \"\"\"Test a dict match using a user-defined comparison function.\"\"\" expected = {'key':",
"actual, expected, description='Dictmatch passes when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self,",
"actual, expected, description='Dictmatch fails because 123 != \"123') assert not dict_ns.match( actual, expected,",
"within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for a dict",
"because of # the type difference, despite the numeric values being equal. actual[38]",
"assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0, 1,",
"= {'key': 123} actual = expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch of",
"dict_ns.match( actual, expected, description='Keep all comparisons by default') assert len(dict_ns.result.entries) == 1 dict_assert",
"float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed and untyped FIX",
"description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test controlling report modes for FIX match.\"\"\"",
"typed match. actual[38] = '1000000' assert not fix_ns.match( actual, expected, description='Failing str/int comparison')",
"\"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the match",
"for i in range(10)} actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual'",
"for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the match method against",
"description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1",
"testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import",
"class AssertionOrder(object): @testcase def case(self, env, result): summary = result.subresult() first = result.subresult()",
"len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual,",
"check_types comparison method the assertion will fail. \"\"\" expected = {'key': 123} actual",
"isinstance(entry, dict) and entry['meta_type'] == 'assertion') for idx, entry in enumerate(assertions): assert entry['description']",
"comparison') # Change the type to a float. The match should still fail",
"expected, description='Keep all comparisons by default') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft()",
"default') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert",
"expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with a mocked out result object.\"\"\" mock_result",
"should fail since we are performing a typed match. actual[38] = '1000000' assert",
"a typed match. actual[38] = '1000000' assert not fix_ns.match( actual, expected, description='Failing str/int",
"ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert =",
"expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed and",
"assert dict_ns.match( actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected,",
"comparison function.\"\"\" expected = {'key': 174.24} actual = {'key': 174.87} tolerance = 1.0",
"ints and floats can be equal if they refer to the same numeric",
"actual, expected, description='Values are not exactly equal') assert dict_ns.match( actual, expected, description='Values are",
"range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3",
"description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes",
"\"\"\" expected = {'key': 123} actual = expected.copy() assert dict_ns.match( actual, expected, description='Basic",
"range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert",
"str. The assert # should fail since we are performing a typed match.",
"idx, entry in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace",
"MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so",
"matches between untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44,",
"testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the match method",
"(44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match') def test_report_modes(self, fix_ns): \"\"\"Test",
"despite the numeric values being equal. actual[38] = 1000000.0 assert not fix_ns.match( actual,",
"types that do not compare equal - in this case, 123 should not",
"expected, description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch",
"== 3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries)",
"2]) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert",
"typed FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True)",
"MultiTest from testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object): @testcase def case(self, env,",
"expected = {'key': 123} actual = {'key': '123'} assert not dict_ns.match( actual, expected,",
"ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert",
"123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes since the numeric values are equal.')",
"mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for",
"dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\"",
"description='Keep all comparisons by default') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert",
"use of the check_types comparison method the assertion will fail. \"\"\" expected =",
"assert not dict_ns.match( actual, expected, description='Dictmatch with string conversion fails due to '",
"'D'), (38, '1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38, '1000000'),",
"report modes for a dict match.\"\"\" expected = {'key{}'.format(i): i for i in",
"def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed and untyped FIX messages.\"\"\" expected",
"actual, expected, description='Basic dictmatch of identical dicts passes') assert dict_ns.match( actual, expected, description='Force",
"== 123.0. However if type-checking is forced by use of the check_types comparison",
"comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert =",
"in range(10)) actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not",
"def fix_ns(): \"\"\"FIX namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock()",
"string conversion fails due to ' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def",
"they refer to the same numeric value - in this case, 123 ==",
"assert not dict_ns.match( actual, expected, description='Dictmatch fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types'])",
"testcase, testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils import comparison, testing @testsuite class",
"forced by use of the check_types comparison method the assertion will fail. \"\"\"",
"assert not dict_ns.match( actual, expected, description='Values are not exactly equal') assert dict_ns.match( actual,",
"dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries)",
"len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit",
"actual = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected,",
"expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not fix_ns.match( actual, expected, description='Keep",
"\"\"\"Unit tests for the testplan.testing.multitest.result module.\"\"\" import collections import mock import pytest from",
"- in this case, 123 should not match \"123\". \"\"\" expected = {'key':",
"pytest from testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite import testcase, testsuite from",
"collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self,",
"mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes when values are converted to",
"'125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns):",
"exactly equal') assert dict_ns.match( actual, expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def",
"testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX",
"\"\"\"Test FIX matches between typed FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38,",
"@pytest.fixture def dict_ns(): \"\"\"Dict namespace with a mocked out result object.\"\"\" mock_result =",
"assert dict_ns.match( actual, expected, description='Basic dictmatch of identical dicts passes') assert dict_ns.match( actual,",
"method against identical expected and actual dicts. \"\"\" expected = {'key': 123} actual",
"for idx, entry in enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict",
"module.\"\"\" import collections import mock import pytest from testplan.testing.multitest import result as result_mod",
"not exactly equal') assert dict_ns.match( actual, expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance)",
"= collections.deque() return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def",
"fail because of # the type difference, despite the numeric values being equal.",
"value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch with string conversion fails due to",
"description='Dictmatch with string conversion fails due to ' 'different string representations of int/float.',",
"@testcase def case(self, env, result): summary = result.subresult() first = result.subresult() second =",
"expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed FIX",
"range(10)} actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not dict_ns.match(",
"should still fail because of # the type difference, despite the numeric values",
"assertion will fail. \"\"\" expected = {'key': 123} actual = {'key': 123.0} assert",
"The assert # should fail since we are performing a typed match. actual[38]",
"and floats can be equal if they refer to the same numeric value",
"match.\"\"\" expected = testing.FixMessage((i, (25 * i) - 4) for i in range(10))",
"result.true(first.passed, 'Report passed so far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest =",
"['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2', 'Report passed so far.'] # pylint: disable=invalid-sequence-index assertions",
"actual, expected, description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\"",
"FIX match') # Now change the type of the actual 38 key's value",
"ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert",
"value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values to strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def",
"for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert",
"actual = expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch of identical dicts passes')",
"import comparison, testing @testsuite class AssertionOrder(object): @testcase def case(self, env, result): summary =",
"assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object):",
"fix_ns.match(actual, expected, description='Basic FIX match') # Now change the type of the actual",
"not fix_ns.match( actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches",
"result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so",
"assert fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert len(fix_ns.result.entries) ==",
"(44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True)",
"'expected' actual['wrong'] = 'actual' assert not dict_ns.match( actual, expected, description='Keep all comparisons by",
"of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values to strings before comparing',",
"== 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1 class TestFIXNamespace(object): \"\"\"Unit testcases",
"we are performing a typed match. actual[38] = '1000000' assert not fix_ns.match( actual,",
"rhs): \"\"\"Check that both values are within a given tolerance range.\"\"\" return abs(lhs",
"\"\"\"Test FIX matches between typed and untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35,",
"same numeric value - in this case, 123 == 123.0. However if type-checking",
"class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test the match method against identical expected and",
"def test_custom_match(self, dict_ns): \"\"\"Test a dict match using a user-defined comparison function.\"\"\" expected",
"expected, description='Values are not exactly equal') assert dict_ns.match( actual, expected, description='Values are equal",
"are performing a typed match. actual[38] = '1000000' assert not fix_ns.match( actual, expected,",
"because 123 != \"123') assert not dict_ns.match( actual, expected, description='Dictmatch fails due to",
"tolerance range.\"\"\" return abs(lhs - rhs) < tolerance assert not dict_ns.match( actual, expected,",
"values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test a dict match",
"strings before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the match method by",
"modes for FIX match.\"\"\" expected = testing.FixMessage((i, (25 * i) - 4) for",
"== 11 assert dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in",
"not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert",
"performing a typed match. actual[38] = '1000000' assert not fix_ns.match( actual, expected, description='Failing",
"comparisons', include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert",
"assert fix_ns.match(actual, expected, description='Basic FIX match') # Now change the type of the",
"assert dict_ns.match( actual, expected, description='Dictmatch passes since the numeric values are equal.') assert",
"description='Failing str/int comparison') # Change the type to a float. The match should",
"4) for i in range(10)) actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] =",
"match. actual[38] = '1000000' assert not fix_ns.match( actual, expected, description='Failing str/int comparison') #",
"numeric values are equal.') assert not dict_ns.match( actual, expected, description='Dictmatch fails when type",
"expected, description='Dictmatch passes since the numeric values are equal.') assert not dict_ns.match( actual,",
"assert dict_ns.match( actual, expected, description='Dictmatch passes when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify'])",
"{'key': 123} actual = {'key': '123'} assert not dict_ns.match( actual, expected, description='Dictmatch fails",
"dict match.\"\"\" expected = {'key{}'.format(i): i for i in range(10)} actual = expected.copy()",
"FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual",
"= 1000000.0 assert not fix_ns.match( actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns):",
"expected = {'key{}'.format(i): i for i in range(10)} actual = expected.copy() expected['wrong'] =",
"within a given tolerance range.\"\"\" return abs(lhs - rhs) < tolerance assert not",
"not compare equal - in this case, 123 should not match \"123\". \"\"\"",
"expected, description='Failing str/int comparison') # Change the type to a float. The match",
"fail. \"\"\" expected = {'key': 123} actual = {'key': 123.0} assert dict_ns.match( actual,",
"class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX",
"result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.') if",
"if isinstance(entry, dict) and entry['meta_type'] == 'assertion') for idx, entry in enumerate(assertions): assert",
"expected, description='Dictmatch passes when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns):",
"2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3",
"second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report",
"equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for a",
"import MultiTest from testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object): @testcase def case(self,",
"floats can be equal if they refer to the same numeric value -",
"test_custom_match(self, dict_ns): \"\"\"Test a dict match using a user-defined comparison function.\"\"\" expected =",
"assert not dict_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1",
"assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for",
"125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') # Now",
"mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.DictNamespace(mock_result) @pytest.fixture",
"value to str. The assert # should fail since we are performing a",
"dicts. \"\"\" expected = {'key': 123} actual = expected.copy() assert dict_ns.match( actual, expected,",
"dict_ns.match( actual, expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test",
"dict_ns): \"\"\" Test the match method against identical expected and actual dicts. \"\"\"",
"= expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') # Now change the type",
"class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns): \"\"\" Test",
"== 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not dict_ns.match( actual,",
"expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not dict_ns.match( actual, expected, description='Keep all",
"do not compare equal - in this case, 123 should not match \"123\".",
"assert not fix_ns.match( actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX",
"actual, expected, description='Keep all comparisons by default') assert len(fix_ns.result.entries) == 1 dict_assert =",
"fix_ns.match( actual, expected, description='Keep all comparisons by default') assert len(fix_ns.result.entries) == 1 dict_assert",
"not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert",
"match using a user-defined comparison function.\"\"\" expected = {'key': 174.24} actual = {'key':",
"expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert not fix_ns.match( actual, expected, description='Keep all",
"in this case, 123 == 123.0. However if type-checking is forced by use",
"== 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not fix_ns.match( actual,",
"assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for",
"type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes when values are converted",
"def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1',",
"testplan.testing.multitest.result module.\"\"\" import collections import mock import pytest from testplan.testing.multitest import result as",
"so far.'] # pylint: disable=invalid-sequence-index assertions = ( entry for entry in mtest.report.flatten()",
"that can be compared. Due to duck-typing, ints and floats can be equal",
"forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch with string conversion fails due",
"function.\"\"\" expected = {'key': 174.24} actual = {'key': 174.87} tolerance = 1.0 def",
"1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not fix_ns.match( actual, expected,",
"due to ' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\"",
"testplan.testing.multitest import MultiTest from testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object): @testcase def",
"123.0. However if type-checking is forced by use of the check_types comparison method",
"passed so far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()])",
"'D'), (38, '1000000'), (44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX",
"expected, description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report",
"test_fail_match(self, dict_ns): \"\"\" Test the match method for types that do not compare",
"i in range(10)) actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] = 'actual' assert",
"expected, description='Dictmatch with string conversion fails due to ' 'different string representations of",
"dict_ns.match( actual, expected, description='Basic dictmatch of identical dicts passes') assert dict_ns.match( actual, expected,",
"description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed and untyped",
"'actual' assert not fix_ns.match( actual, expected, description='Keep all comparisons by default') assert len(fix_ns.result.entries)",
"fix_ns(): \"\"\"FIX namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries",
"to the same numeric value - in this case, 123 == 123.0. However",
"actual, expected, description='Dictmatch with string conversion fails due to ' 'different string representations",
"FIX matches between untyped FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'),",
"assert not dict_ns.match( actual, expected, description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert",
"test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run() expected = ['AssertionFirst1', 'AssertionFirst2', 'AssertionSecond', 'AssertionMain1', 'AssertionMain2',",
"= {'key': 123} actual = {'key': '123'} assert not dict_ns.match( actual, expected, description='Dictmatch",
"of the actual 38 key's value to str. The assert # should fail",
"fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed",
"return result_mod.FixNamespace(mock_result) class TestDictNamespace(object): \"\"\"Unit testcases for the result.DictNamespace class.\"\"\" def test_basic_match(self, dict_ns):",
"len(dict_assert.comparison) == 11 assert dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i",
"= fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert not fix_ns.match( actual, expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard",
"(38, '1000000'), (44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match')",
"pylint: disable=invalid-sequence-index assertions = ( entry for entry in mtest.report.flatten() if isinstance(entry, dict)",
"before comparing', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_duck_match(self, dict_ns): \"\"\" Test the match method by seting",
"= {'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes since the numeric values",
"testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object): @testcase def case(self, env, result): summary",
"'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the match",
"tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are within a",
"range.\"\"\" return abs(lhs - rhs) < tolerance assert not dict_ns.match( actual, expected, description='Values",
"expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert",
"= {'key': 123} actual = {'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes",
"and entry['meta_type'] == 'assertion') for idx, entry in enumerate(assertions): assert entry['description'] == expected[idx]",
"if they refer to the same numeric value - in this case, 123",
"enumerate(assertions): assert entry['description'] == expected[idx] @pytest.fixture def dict_ns(): \"\"\"Dict namespace with a mocked",
"actual, expected, description='Dictmatch fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match(",
"((35, 'D'), (38, '1000000'), (44, '125.83'))) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic",
"report modes for FIX match.\"\"\" expected = testing.FixMessage((i, (25 * i) - 4)",
"mock import pytest from testplan.testing.multitest import result as result_mod from testplan.testing.multitest.suite import testcase,",
"FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, '125.83'))) actual =",
"actual = {'key': '123'} assert not dict_ns.match( actual, expected, description='Dictmatch fails because 123",
"expected and actual dicts. \"\"\" expected = {'key': 123} actual = expected.copy() assert",
"a given tolerance range.\"\"\" return abs(lhs - rhs) < tolerance assert not dict_ns.match(",
"still fail because of # the type difference, despite the numeric values being",
"fix_ns): \"\"\"Test controlling report modes for FIX match.\"\"\" expected = testing.FixMessage((i, (25 *",
"report_mode=comparison.ReportOptions.NO_IGNORED) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 3 assert",
"testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped",
"actual dicts. \"\"\" expected = {'key': 123} actual = expected.copy() assert dict_ns.match( actual,",
"not dict_ns.match( actual, expected, description='Dictmatch fails because 123 != \"123') assert not dict_ns.match(",
"dict_ns.match( actual, expected, description='Dictmatch passes since the numeric values are equal.') assert not",
"from testplan.testing.multitest import MultiTest from testplan.common.utils import comparison, testing @testsuite class AssertionOrder(object): @testcase",
"def dict_ns(): \"\"\"Dict namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock()",
"actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') # Now change the",
"description='Dictmatch passes when values are converted to strings', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_custom_match(self, dict_ns): \"\"\"Test",
"== 1 class TestFIXNamespace(object): \"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns):",
"description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert values to strings",
"description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] == 'assertion') for idx, entry in enumerate(assertions):",
"return abs(lhs - rhs) < tolerance assert not dict_ns.match( actual, expected, description='Values are",
"1000000.0 assert not fix_ns.match( actual, expected, description='Failing float/int comparison') def test_mixed_fixmatch(self, fix_ns): \"\"\"Test",
"between typed FIX messages.\"\"\" expected = testing.FixMessage( ((35, 'D'), (38, 1000000), (44, 125.83)),",
"import collections import mock import pytest from testplan.testing.multitest import result as result_mod from",
"= {'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values",
"fix_ns): \"\"\"Test FIX matches between typed and untyped FIX messages.\"\"\" expected = testing.FixMessage(",
"description='Values are equal within tolerance', value_cmp_func=cmp_with_tolerance) def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes",
"result.subresult() first = result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2')",
"@pytest.fixture def fix_ns(): \"\"\"FIX namespace with a mocked out result object.\"\"\" mock_result =",
"test_mixed_fixmatch(self, fix_ns): \"\"\"Test FIX matches between typed and untyped FIX messages.\"\"\" expected =",
"namespace with a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque()",
"1, 2]) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11",
"env, result): summary = result.subresult() first = result.subresult() second = result.subresult() second.true(True, 'AssertionSecond')",
"'Report passed so far.'] # pylint: disable=invalid-sequence-index assertions = ( entry for entry",
"Test the match method for types that do not compare equal - in",
"actual, expected, description='Dictmatch fails due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected,",
"second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2')",
"len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match( actual,",
"not dict_ns.match( actual, expected, description='Dictmatch with string conversion fails due to ' 'different",
"fix_ns.match( actual, expected, description='Failing str/int comparison') # Change the type to a float.",
"174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check that both values are within",
"the match method against identical expected and actual dicts. \"\"\" expected = {'key':",
"should not match \"123\". \"\"\" expected = {'key': 123} actual = {'key': '123'}",
"case, 123 should not match \"123\". \"\"\" expected = {'key': 123} actual =",
"= 'actual' assert not dict_ns.match( actual, expected, description='Keep all comparisons by default') assert",
"actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test",
"123} actual = expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch of identical dicts",
"expected = testing.FixMessage((i, (25 * i) - 4) for i in range(10)) actual",
"fails due to ' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns):",
"so far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder', suites=[AssertionOrder()]) mtest.run()",
"expected, report_mode=comparison.ReportOptions.FAILS_ONLY, description='Discard passing comparisons') assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert",
"== 11 assert fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0, 1, 2]) assert",
"- 4) for i in range(10)) actual = expected.copy() expected['wrong'] = 'expected' actual['wrong']",
"result_mod from testplan.testing.multitest.suite import testcase, testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils import",
"dict_ns): \"\"\" Test the match method by seting different types that can be",
"i for i in range(10)} actual = expected.copy() expected['wrong'] = 'expected' actual['wrong'] =",
"due to type mismatch', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes when values",
"of # the type difference, despite the numeric values being equal. actual[38] =",
"in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11",
"'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected, description='Basic",
"(38, '1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44,",
"seting different types that can be compared. Due to duck-typing, ints and floats",
"passing comparisons') assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 1",
"testing @testsuite class AssertionOrder(object): @testcase def case(self, env, result): summary = result.subresult() first",
"include_tags=[0, 1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"entry in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] == 'assertion') for idx, entry",
"assert # should fail since we are performing a typed match. actual[38] =",
"comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft()",
"conversion fails due to ' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self,",
"((35, 'D'), (38, 1000000), (44, 125.83)), typed_values=True) actual = expected.copy() assert fix_ns.match(actual, expected,",
"expected.copy() assert fix_ns.match(actual, expected, description='Basic FIX match') def test_typed_fixmatch(self, fix_ns): \"\"\"Test FIX matches",
"of identical dicts passes') assert dict_ns.match( actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types'])",
"expected.copy() assert dict_ns.match( actual, expected, description='Basic dictmatch of identical dicts passes') assert dict_ns.match(",
"1, 2], report_mode=comparison.ReportOptions.NO_IGNORED) assert len(fix_ns.result.entries) == 1 dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) ==",
"123} actual = {'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes since the",
"refer to the same numeric value - in this case, 123 == 123.0.",
"will fail. \"\"\" expected = {'key': 123} actual = {'key': 123.0} assert dict_ns.match(",
"dict_assert = fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Keep ignored",
"123 != \"123') assert not dict_ns.match( actual, expected, description='Dictmatch fails due to type",
"fix_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert fix_ns.match( actual, expected, description='Keep ignored comparisons', include_tags=[0,",
"value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Dictmatch passes when values are converted to strings',",
"def test_fail_match(self, dict_ns): \"\"\" Test the match method for types that do not",
"'Report passed so far.') if first.passed: summary.append(second) result.prepend(summary) def test_assertion_orders(): mtest = MultiTest(name='AssertionsOrder',",
"= {'key': '123'} assert not dict_ns.match( actual, expected, description='Dictmatch fails because 123 !=",
"for i in range(3)]) assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison)",
"of the check_types comparison method the assertion will fail. \"\"\" expected = {'key':",
"actual = {'key': 123.0} assert dict_ns.match( actual, expected, description='Dictmatch passes since the numeric",
"the match method for types that do not compare equal - in this",
"{'key': 174.24} actual = {'key': 174.87} tolerance = 1.0 def cmp_with_tolerance(lhs, rhs): \"\"\"Check",
"expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries) == 1",
"against identical expected and actual dicts. \"\"\" expected = {'key': 123} actual =",
"' 'different string representations of int/float.', value_cmp_func=comparison.COMPARE_FUNCTIONS['stringify']) def test_fail_match(self, dict_ns): \"\"\" Test the",
"{'key': '123'} assert not dict_ns.match( actual, expected, description='Dictmatch fails because 123 != \"123')",
"actual, expected, description='Keep ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)]) assert len(dict_ns.result.entries) ==",
"result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between untyped FIX messages.\"\"\" expected",
"dict_ns.match( actual, expected, description='Discard ignored comparisons', include_keys=['key{}'.format(i) for i in range(3)], report_mode=comparison.ReportOptions.NO_IGNORED) assert",
"the type difference, despite the numeric values being equal. actual[38] = 1000000.0 assert",
"assert len(dict_ns.result.entries) == 1 dict_assert = dict_ns.result.entries.popleft() assert len(dict_assert.comparison) == 11 assert dict_ns.match(",
"\"\"\"Check that both values are within a given tolerance range.\"\"\" return abs(lhs -",
"first = result.subresult() second = result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True,",
"'1000000'), (44, '125.83')), typed_values=False) actual = testing.FixMessage( ((35, 'D'), (38, '1000000'), (44, 125.83)),",
"a dict match.\"\"\" expected = {'key{}'.format(i): i for i in range(10)} actual =",
"actual 38 key's value to str. The assert # should fail since we",
"dict_ns.match( actual, expected, description='Dictmatch fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not",
"= result.subresult() second.true(True, 'AssertionSecond') result.true(True, 'AssertionMain1') result.true(True, 'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first)",
"value - in this case, 123 == 123.0. However if type-checking is forced",
"'AssertionMain2') first.true(True, 'AssertionFirst1') first.true(True, 'AssertionFirst2') summary.append(first) result.true(first.passed, 'Report passed so far.') if first.passed:",
"'AssertionMain2', 'Report passed so far.'] # pylint: disable=invalid-sequence-index assertions = ( entry for",
"import testcase, testsuite from testplan.testing.multitest import MultiTest from testplan.common.utils import comparison, testing @testsuite",
"def test_report_modes(self, dict_ns): \"\"\"Test controlling report modes for a dict match.\"\"\" expected =",
"dict_ns.match( actual, expected, description='Force type-check of values', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert dict_ns.match( actual, expected, description='Convert",
"((35, 'D'), (38, '1000000'), (44, 125.83)), typed_values=True) assert fix_ns.match(actual, expected, description='Mixed FIX match')",
"a mocked out result object.\"\"\" mock_result = mock.MagicMock() mock_result.entries = collections.deque() return result_mod.FixNamespace(mock_result)",
"fails when type comparison is forced.', value_cmp_func=comparison.COMPARE_FUNCTIONS['check_types']) assert not dict_ns.match( actual, expected, description='Dictmatch",
"\"\"\"Unit testcases for the result.FixNamespace class.\"\"\" def test_untyped_fixmatch(self, fix_ns): \"\"\"Test FIX matches between",
"for entry in mtest.report.flatten() if isinstance(entry, dict) and entry['meta_type'] == 'assertion') for idx,",
"\"\"\" Test the match method for types that do not compare equal -",
"= testing.FixMessage((i, (25 * i) - 4) for i in range(10)) actual ="
] |
[
"@click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date:",
"file Args: station: 4-character site (base) identifier start_date: datetime object end_date: datetime object",
"raise ValueError('Date is too early') runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run()",
"datetime object \"\"\" try: if start_date > end_date: raise ValueError('Start date is past",
"Args: station: 4-character site (base) identifier start_date: datetime object end_date: datetime object \"\"\"",
"early') runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run() except Exception as e:",
"start_date.year < 1994 or end_date.year < 1994: raise ValueError('Date is too early') runner",
"datetime object end_date: datetime object \"\"\" try: if start_date > end_date: raise ValueError('Start",
"runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run() except Exception as e: print(\"Error:\",",
"import click from datetime import datetime from typing import List import string from",
"RINEX files from FTP server and merges them into one file Args: station:",
"start_date > datetime.now() or end_date > datetime.now(): raise ValueError( 'FTP does not have",
"that extend all the way to your end date yet.') if start_date.year <",
"type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date: datetime): \"\"\"",
"start_date > end_date: raise ValueError('Start date is past end date') if start_date >",
"one file Args: station: 4-character site (base) identifier start_date: datetime object end_date: datetime",
"datetime, end_date: datetime): \"\"\" Downloads RINEX files from FTP server and merges them",
"import string from src.Runner import RinexRunner from src.Downloader import RinexDownloader from src.Merger import",
"raise ValueError('Start date is past end date') if start_date > datetime.now() or end_date",
"not have log files that extend all the way to your end date",
"< 1994: raise ValueError('Date is too early') runner = RinexRunner(station, start_date, end_date, RinexDownloader,",
"> end_date: raise ValueError('Start date is past end date') if start_date > datetime.now()",
"or end_date.year < 1994: raise ValueError('Date is too early') runner = RinexRunner(station, start_date,",
"the way to your end date yet.') if start_date.year < 1994 or end_date.year",
"from src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station:",
"cli(station: str, start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX files from FTP server",
"Downloads RINEX files from FTP server and merges them into one file Args:",
"from src.Runner import RinexRunner from src.Downloader import RinexDownloader from src.Merger import RinexMerger @click.command()",
"end_date: datetime object \"\"\" try: if start_date > end_date: raise ValueError('Start date is",
"have log files that extend all the way to your end date yet.')",
"date is past end date') if start_date > datetime.now() or end_date > datetime.now():",
"and merges them into one file Args: station: 4-character site (base) identifier start_date:",
"import datetime from typing import List import string from src.Runner import RinexRunner from",
"datetime import datetime from typing import List import string from src.Runner import RinexRunner",
"if start_date.year < 1994 or end_date.year < 1994: raise ValueError('Date is too early')",
"end_date: raise ValueError('Start date is past end date') if start_date > datetime.now() or",
"merges them into one file Args: station: 4-character site (base) identifier start_date: datetime",
"> datetime.now(): raise ValueError( 'FTP does not have log files that extend all",
"end date yet.') if start_date.year < 1994 or end_date.year < 1994: raise ValueError('Date",
"end_date.year < 1994: raise ValueError('Date is too early') runner = RinexRunner(station, start_date, end_date,",
"RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime,",
"(base) identifier start_date: datetime object end_date: datetime object \"\"\" try: if start_date >",
"identifier start_date: datetime object end_date: datetime object \"\"\" try: if start_date > end_date:",
"type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX files from",
"ValueError('Start date is past end date') if start_date > datetime.now() or end_date >",
"raise ValueError( 'FTP does not have log files that extend all the way",
"files from FTP server and merges them into one file Args: station: 4-character",
"src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str,",
"ValueError('Date is too early') runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run() except",
"type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX",
"def cli(station: str, start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX files from FTP",
"< 1994 or end_date.year < 1994: raise ValueError('Date is too early') runner =",
"station: 4-character site (base) identifier start_date: datetime object end_date: datetime object \"\"\" try:",
"datetime.now() or end_date > datetime.now(): raise ValueError( 'FTP does not have log files",
"past end date') if start_date > datetime.now() or end_date > datetime.now(): raise ValueError(",
"try: if start_date > end_date: raise ValueError('Start date is past end date') if",
"does not have log files that extend all the way to your end",
"them into one file Args: station: 4-character site (base) identifier start_date: datetime object",
"server and merges them into one file Args: station: 4-character site (base) identifier",
"to your end date yet.') if start_date.year < 1994 or end_date.year < 1994:",
"4-character site (base) identifier start_date: datetime object end_date: datetime object \"\"\" try: if",
"from datetime import datetime from typing import List import string from src.Runner import",
"click from datetime import datetime from typing import List import string from src.Runner",
"if start_date > datetime.now() or end_date > datetime.now(): raise ValueError( 'FTP does not",
"= RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run() except Exception as e: print(\"Error:\", e)",
"str, start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX files from FTP server and",
"@click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date: datetime):",
"site (base) identifier start_date: datetime object end_date: datetime object \"\"\" try: if start_date",
"log files that extend all the way to your end date yet.') if",
"extend all the way to your end date yet.') if start_date.year < 1994",
"> datetime.now() or end_date > datetime.now(): raise ValueError( 'FTP does not have log",
"too early') runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run() except Exception as",
"typing import List import string from src.Runner import RinexRunner from src.Downloader import RinexDownloader",
"List import string from src.Runner import RinexRunner from src.Downloader import RinexDownloader from src.Merger",
"way to your end date yet.') if start_date.year < 1994 or end_date.year <",
"date') if start_date > datetime.now() or end_date > datetime.now(): raise ValueError( 'FTP does",
"@click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date: datetime): \"\"\" Downloads",
"import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date:",
"end_date: datetime): \"\"\" Downloads RINEX files from FTP server and merges them into",
"start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX files from FTP server and merges",
"object \"\"\" try: if start_date > end_date: raise ValueError('Start date is past end",
"import RinexRunner from src.Downloader import RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station', type=str)",
"all the way to your end date yet.') if start_date.year < 1994 or",
"end date') if start_date > datetime.now() or end_date > datetime.now(): raise ValueError( 'FTP",
"src.Downloader import RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date',",
"yet.') if start_date.year < 1994 or end_date.year < 1994: raise ValueError('Date is too",
"your end date yet.') if start_date.year < 1994 or end_date.year < 1994: raise",
"date yet.') if start_date.year < 1994 or end_date.year < 1994: raise ValueError('Date is",
"ValueError( 'FTP does not have log files that extend all the way to",
"1994: raise ValueError('Date is too early') runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger)",
"files that extend all the way to your end date yet.') if start_date.year",
"from FTP server and merges them into one file Args: station: 4-character site",
"import RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ']))",
"into one file Args: station: 4-character site (base) identifier start_date: datetime object end_date:",
"string from src.Runner import RinexRunner from src.Downloader import RinexDownloader from src.Merger import RinexMerger",
"object end_date: datetime object \"\"\" try: if start_date > end_date: raise ValueError('Start date",
"\"\"\" Downloads RINEX files from FTP server and merges them into one file",
"@click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def cli(station: str, start_date: datetime, end_date: datetime): \"\"\" Downloads RINEX files",
"RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) @click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ'])) def",
"is past end date') if start_date > datetime.now() or end_date > datetime.now(): raise",
"from typing import List import string from src.Runner import RinexRunner from src.Downloader import",
"from src.Downloader import RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%dT%H:%M:%SZ']))",
"start_date: datetime object end_date: datetime object \"\"\" try: if start_date > end_date: raise",
"import List import string from src.Runner import RinexRunner from src.Downloader import RinexDownloader from",
"'FTP does not have log files that extend all the way to your",
"or end_date > datetime.now(): raise ValueError( 'FTP does not have log files that",
"datetime.now(): raise ValueError( 'FTP does not have log files that extend all the",
"is too early') runner = RinexRunner(station, start_date, end_date, RinexDownloader, RinexMerger) runner.run() except Exception",
"if start_date > end_date: raise ValueError('Start date is past end date') if start_date",
"RinexRunner from src.Downloader import RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station', type=str) @click.argument('start_date',",
"\"\"\" try: if start_date > end_date: raise ValueError('Start date is past end date')",
"src.Runner import RinexRunner from src.Downloader import RinexDownloader from src.Merger import RinexMerger @click.command() @click.argument('station',",
"datetime): \"\"\" Downloads RINEX files from FTP server and merges them into one",
"<gh_stars>0 import click from datetime import datetime from typing import List import string",
"1994 or end_date.year < 1994: raise ValueError('Date is too early') runner = RinexRunner(station,",
"end_date > datetime.now(): raise ValueError( 'FTP does not have log files that extend",
"FTP server and merges them into one file Args: station: 4-character site (base)",
"datetime from typing import List import string from src.Runner import RinexRunner from src.Downloader"
] |
[
"'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond',",
"'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth',",
"'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond',",
"'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] |",
"'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange',",
"'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth',",
"'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange',",
"'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong',",
"'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond',",
"'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond',",
"'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst',",
"'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond',",
"'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange',",
"########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond',",
"= {} ########################################################################## ismir2020featsets['ismir2020_all_lyr_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond',",
"'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ##########################################################################",
"'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth',",
"'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth',",
"'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond',",
"'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond',",
"'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = {",
"'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth',",
"'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond',",
"'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth',",
"'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth',",
"'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth',",
"'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation',",
"'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond',",
"'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst',",
"'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst',",
"'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', }",
"'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal',",
"'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth',",
"'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird',",
"= { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird',",
"'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth',",
"'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird',",
"'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth',",
"'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth',",
"'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond',",
"'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst',",
"'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird',",
"'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond',",
"'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird',",
"'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond',",
"'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird',",
"'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong',",
"'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird',",
"########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth',",
"########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth',",
"'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth',",
"'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst',",
"'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth',",
"'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = {",
"'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst',",
"'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond',",
"ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird',",
"'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst',",
"'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond',",
"'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird',",
"'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth',",
"| ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics'] #for k in ismir2020featsets.keys(): # print(k)",
"} ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst',",
"'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth',",
"{ 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset',",
"ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth',",
"'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth',",
"'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond',",
"'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst',",
"'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth',",
"'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth',",
"'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ##########################################################################",
"'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird',",
"{ 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth',",
"'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator',",
"'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond',",
"'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth',",
"'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = {",
"'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all']",
"'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth',",
"'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond',",
"'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth',",
"'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird',",
"'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth',",
"'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending',",
"'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation',",
"'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth',",
"'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap',",
"'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond',",
"########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst',",
"'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond',",
"'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird',",
"} ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird',",
"'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth',",
"'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = {",
"########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth',",
"'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount',",
"'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond',",
"'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm']",
"'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond',",
"'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ##########################################################################",
"'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', }",
"'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst',",
"'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird',",
"'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth',",
"'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst',",
"'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond',",
"'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth',",
"} ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal',",
"'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth',",
"'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird',",
"'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth',",
"'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth',",
"'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond',",
"'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird',",
"'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth',",
"'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird',",
"'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond',",
"'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird',",
"'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst',",
"'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond',",
"'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth',",
"'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst',",
"'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth',",
"'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond',",
"########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth',",
"'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond',",
"'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal',",
"'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth',",
"'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth',",
"'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth',",
"'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth',",
"'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst',",
"'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird',",
"'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth',",
"'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond',",
"'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond',",
"ismir2020featsets['ismir2020_all_lyr_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth',",
"'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall',",
"'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst',",
"'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond',",
"'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset',",
"'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = {",
"'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending',",
"ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics'] #for k in",
"'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth',",
"'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth',",
"'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ##########################################################################",
"'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth',",
"'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = {",
"'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird',",
"'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus',",
"'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch']",
"= ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics'] #for k in ismir2020featsets.keys():",
"'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth',",
"'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst',",
"'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond',",
"########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth',",
"'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset',",
"'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird',",
"'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst',",
"'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond',",
"'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst',",
"'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', }",
"'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth',",
"'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] =",
"'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond',",
"ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics'] #for k in ismir2020featsets.keys(): #",
"'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst',",
"'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond',",
"'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth',",
"'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration',",
"'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall']",
"'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst',",
"'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth',",
"'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth',",
"'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth',",
"'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth',",
"'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase',",
"'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird',",
"'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst',",
"'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth',",
"'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst',",
"ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth',",
"'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird',",
"'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond',",
"'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth',",
"'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird',",
"'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm']",
"'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth',",
"'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird',",
"'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird',",
"'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond',",
"'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst',",
"{ 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth',",
"'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels']",
"'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird',",
"'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst',",
"'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm']",
"'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm']",
"'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth',",
"'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator',",
"ismir2020featsets = {} ########################################################################## ismir2020featsets['ismir2020_all_lyr_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst',",
"} ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird',",
"{} ########################################################################## ismir2020featsets['ismir2020_all_lyr_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird',",
"'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth',",
"'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond',",
"'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond',",
"'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird',",
"'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird',",
"'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch']",
"'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth',",
"'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond',",
"'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth',",
"'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth',",
"'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth',",
"'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth',",
"'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong',",
"'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond',",
"'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall',",
"'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth',",
"'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration',",
"'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst',",
"} ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird',",
"'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr']",
"'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond',",
"'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth',",
"{ 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond',",
"'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird',",
"'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst',",
"'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond',",
"'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird',",
"'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] |",
"'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst',",
"'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird',",
"'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth',",
"'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth',",
"'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth',",
"'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth',",
"'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth',",
"'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst',",
"'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth',",
"'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth',",
"'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond',",
"'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird',",
"'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst',",
"'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst',",
"ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth',",
"'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth',",
"'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird',",
"'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] =",
"'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird',",
"'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth',",
"'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt']",
"'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] =",
"'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth',",
"'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth',",
"'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth',",
"'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird',",
"'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird',",
"'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth',",
"'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst',",
"'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond',",
"'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond',",
"'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond',",
"} ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird',",
"'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending',",
"'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics']",
"'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth',",
"} ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics'] #for",
"ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth',",
"'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst',",
"'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth',",
"'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird',",
"'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth',",
"'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst',",
"'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth',",
"'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird',",
"'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth',",
"'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird',",
"'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst',",
"'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = {",
"########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] = ismir2020featsets['ismir2020_elementarypitch'] | ismir2020featsets['ismir2020_elementaryrhythm'] ismir2020featsets['ismir2020_elementaryall'] = ismir2020featsets['ismir2020_elementarypitchrhythm'] | ismir2020featsets['ismir2020_elementarylyrics'] #for k",
"'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond',",
"'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset',",
"'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird',",
"'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird',",
"<gh_stars>1-10 ismir2020featsets = {} ########################################################################## ismir2020featsets['ismir2020_all_lyr_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth',",
"'grouperfourth', 'grouperfifth', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth', 'pitchreversalfirst',",
"ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth',",
"'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond',",
"'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth',",
"'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond',",
"'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth',",
"'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitchrhythm'] =",
"'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird',",
"'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth', 'pitchproximityfifth',",
"'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth',",
"'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth',",
"'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation',",
"'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond',",
"'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond',",
"'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird', 'diatonicpitchthirdfourth', 'diatonicpitchfourthfifth', 'VosHarmonyfirstsecond', 'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', } ##########################################################################",
"'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst',",
"'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird',",
"= { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset',",
"'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond',",
"'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth',",
"'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth',",
"'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth',",
"'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth',",
"'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator',",
"########################################################################## ismir2020featsets['ismir2020_all_lyr_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth',",
"'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth',",
"'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth',",
"'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond',",
"'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth',",
"'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ##########################################################################",
"'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth',",
"'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird',",
"'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase',",
"'pitchreversalfirst', 'pitchreversalsecond', 'pitchreversalthird', 'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird',",
"'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending',",
"'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth',",
"'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst',",
"'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'meternumerator', 'meterdenominator', 'nextisrestfirst',",
"'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth',",
"'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird',",
"'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', }",
"'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration',",
"'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird',",
"'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird', 'pitchproximityfourth',",
"'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond',",
"'meternumerator', 'meterdenominator', 'nextisrestfirst', 'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst',",
"'noncontentwordthird', 'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth',",
"'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'beatduration', 'beatcount',",
"'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics']",
"'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond',",
"'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth',",
"'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount',",
"'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] =",
"'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird',",
"'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', }",
"'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementaryrhythm'] = { 'meternumerator', 'meterdenominator',",
"'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', }",
"'pitchreversalfourth', 'pitchreversalfifth', 'lbdmfirst', 'lbdmsecond', 'lbdmthird', 'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird',",
"'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond',",
"'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus',",
"} ########################################################################## ismir2020featsets['ismir2020_all_gt'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird',",
"'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond',",
"'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth',",
"'VosHarmonysecondthird', 'VosHarmonythirdfourth', 'VosHarmonyfourthfifth', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird',",
"'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird',",
"'midipitchsecond', 'midipitchthird', 'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth',",
"= { 'meternumerator', 'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth',",
"'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] =",
"'informationcontentfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap',",
"'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasurephrase', 'completesmeasuresong', 'completesbeatphrase', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth', 'grouperfifth',",
"'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth',",
"'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth',",
"'meterdenominator', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst',",
"'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth',",
"'IOIbeatfractionfourthfifth', 'wordstressfirstsecond', 'wordstresssecondthird', 'wordstressthirdfourth', 'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_gt'] =",
"'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'durationcummulation', 'grouperfirst', 'groupersecond',",
"'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset', 'rhyme_beatoffset', 'noncontentwordfirst', 'noncontentwordsecond', 'noncontentwordthird',",
"'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth',",
"'grouperfifth', 'noteoffset', 'beatoffset', 'beatduration', 'beatcount', 'gprsumfirst', 'gprsumsecond', 'gprsumthird', 'gprsumfourth', 'gprsumfifth', 'pitchproximityfirst', 'pitchproximitysecond', 'pitchproximitythird',",
"'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'beatduration', 'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth',",
"ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'registraldirectionchange', 'largetosmall', 'contourreversal', 'beatstrengthfirst', 'beatstrengthsecond',",
"'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond', 'wordstresssecondthird',",
"'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] =",
"'midipitchfourth', 'midipitchfifth', 'intervalfirst', 'intervalsecond', 'intervalthird', 'intervalfourth', 'intervalfifth', 'VosCenterGravityfirst', 'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst',",
"'beatcount', 'beatstrengthfirstsecond', 'beatstrengthsecondthird', 'beatstrengththirdfourth', 'beatstrengthfourthfifth', 'IOIbeatfractionfirstsecond', 'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarypitch'] =",
"'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'informationcontentfirst', 'informationcontentsecond', 'informationcontentthird', 'informationcontentfourth', 'informationcontentfifth', 'contourfirst', 'contoursecond',",
"'noncontentwordfourth', 'noncontentwordfifth', 'wordendfirst', 'wordendsecond', 'wordendthird', 'wordendfourth', 'wordendfifth', 'melismastatefirst', 'melismastatesecond', 'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'wordstressfirstsecond',",
"'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_elementarylyrics'] = { 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth',",
"'VosCenterGravitysecond', 'VosCenterGravitythird', 'VosCenterGravityfourth', 'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth',",
"'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst', 'midipitchsecond', 'midipitchthird',",
"'lbdmfourth', 'lbdmfifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth',",
"'wordstressfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird',",
"'melismastatethird', 'melismastatefourth', 'melismastatefifth', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth', 'diatonicpitchfirstsecond', 'diatonicpitchsecondthird',",
"'IOIbeatfractionsecondthird', 'IOIbeatfractionthirdfourth', 'IOIbeatfractionfourthfifth', 'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_othermodels'] = { 'informationcontentfirst',",
"= { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst', 'diatonicpitchsecond', 'diatonicpitchthird', 'diatonicpitchfourth', 'diatonicpitchfifth', 'midipitchfirst',",
"'informationcontentfirstsecond', 'informationcontentsecondthird', 'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth',",
"'contourreversal', 'isascending', 'isdescending', 'ambitus', 'containsleap', 'intervalsizefirstsecond', 'intervalsizesecondthird', 'intervalsizethirdfourth', 'intervalsizefourthfifth', 'intervaldirfirstsecond', 'intervaldirsecondthird', 'intervaldirthirdfourth', 'intervaldirfourthfifth',",
"'lbdmfourth', 'lbdmfifth', 'wordstressfirst', 'wordstresssecond', 'wordstressthird', 'wordstressfourth', 'wordstressfifth', 'rhymesfirst', 'rhymessecond', 'rhymesthird', 'rhymesfourth', 'rhymesfifth', 'rhyme_noteoffset',",
"'nextisrestsecond', 'nextisrestthird', 'nextisrestfourth', 'nextisrestfifth', 'beatstrengthfirst', 'beatstrengthsecond', 'beatstrengththird', 'beatstrengthfourth', 'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth',",
"'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong', 'completesbeatsong', 'grouperfirst', 'groupersecond', 'grouperthird', 'grouperfourth',",
"'VosCenterGravityfifth', 'VosHarmonyfirst', 'VosHarmonysecond', 'VosHarmonythird', 'VosHarmonyfourth', 'VosHarmonyfifth', 'contourfirst', 'contoursecond', 'contourthird', 'contourfourth', 'contourfifth', 'registraldirectionchange', 'largetosmall',",
"'informationcontentthirdfourth', 'informationcontentfourthfifth', } ########################################################################## ismir2020featsets['ismir2020_all_lyr'] = { 'scaledegreefirst', 'scaledegreesecond', 'scaledegreethird', 'scaledegreefourth', 'scaledegreefifth', 'diatonicpitchfirst',",
"'beatstrengthfifth', 'IOIbeatfractionfirst', 'IOIbeatfractionsecond', 'IOIbeatfractionthird', 'IOIbeatfractionfourth', 'IOIbeatfractionfifth', 'durationcummulation', 'onthebeatfirst', 'onthebeatsecond', 'onthebeatthird', 'onthebeatfourth', 'onthebeatfifth', 'completesmeasuresong',"
] |
[
"apiurl are globals ######################################################################### def getapidata(url, autho): # get the data from the",
"if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\":",
"category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes, \"Pilots\": pilots, \"Devices\": devicesid}",
"apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code --------------- # # gather",
"to the 3 chars ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate =",
"rel = \"v1\" # we use API version 1 # ==============================================# utc =",
"the contestants on each class url3 = getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\")",
"the message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the message digest",
"# auth and apiurl are globals ######################################################################### def getapidata(url, autho): # get the",
"coding: UTF-8 -*- # This module gets that daya from SoaringSpot and prepaeres",
"class if prt: print(\"Class:\", classname, \"\\n\\n\") # search for each class # search",
"digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build the",
"compid) print(\"Loc Name:\", lcname, \"Country: \", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if",
"[] for cl in getemb(cd, 'classes'): # print \"CLCLCL\", cl classname = cl[\"type\"]",
"class url3 = getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") # get the contestants",
"chars code compcountry = country # contry as defaults for pilots # convert",
"in contestants: ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number' in contestants:",
"document def gdata(url, key, prt='no'): global auth # auth and apiurl are globals",
"# soaringspot API URL rel = \"v1\" # we use API version 1",
"= country # contry as defaults for pilots # convert the 2 chars",
"# OGN trackers paired if len(idflarm) == 6: # in case of missing",
"getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] # get the flarm if",
"print(\"Classes:\\n========\\n\\n\") npil = 0 # init the number of pilots classes = []",
"key) # get the data from the HAL document return cd def getemb(base,",
"OGN tracker pair idflarm = livetrk[0:9] ognpair = livetrk[10:] # OGN trackers paired",
"from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth # auth",
"def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href'])",
"# convert to HAL if prt == 'yes': # if print is required",
"now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print",
"print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init the number of pilots",
"= cd['category'] eventname = cd['name'] compid = cd['id'] country = cd['country'] # country",
"to utf8 in order to avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\ \"",
"ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get",
"convert to HAL if prt == 'yes': # if print is required print(json.dumps(j_obj,",
"the number of pilots classes = [] pilots = [] devicesid = \"\"",
"\"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\":",
"get the contest data, first instance cd = gdata(url1, 'contests', prt='no')[0] # get",
"IGC file # see if index day is requestedd # --------------------------------------# # =====",
"idflarm = livetrk # case that just the FlarmID, no piaring if len(livetrk)",
"time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time = datetime.now() #",
"base64.b64encode(os.urandom(36)) # get the once base # build the message message = nonce+date.encode(encoding='utf-8')",
"data from the API server req = urllib.request.Request(url) req.add_header('Authorization', autho) # build the",
"= getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] # get the flarm",
"hemisphere if (latitude < flatil or latitude > flatiu): return (True) else: #",
"[] pilots = [] devicesid = \"\" # Build the tracks and turn",
"OGN type # get the registration from OGN DDB idfreg = getognreg(idflarm[3:9]) if",
"we do not have the registration ID on the soaringspota regi = \"reg_NOTYET\"",
"+= idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country",
"\"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname}",
"to find the SQLITE3 database cwd = os.getcwd() # get the current working",
"2 chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=country) country =",
"= getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '': nation = compcountry else: nation",
"the contestants and task within each class # go thru the different classes",
"requestedd # --------------------------------------# # ===== SETUP parameters =======================# # where to find the",
"chars ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date'] lc =",
"Name:\", lcname, \"Country: \", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\")",
"def soa2rts(RTS, client, secretkey, prt=False): global apiurl global auth date = datetime.now() #",
"return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu): if (flatil == 0.0): return (False)",
"the OGN DDB ognid = getognflarmid(regi) else: # if we do not have",
"the HAL document return cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base,",
"lcname = lc['name'] # location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\",",
"1 pil = {\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3,",
"import socket import os.path from datetime import datetime import pycountry from ognddbfuncs import",
"{\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots as",
"\"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open the url resource j_obj =",
"# print the number of pilots as a reference and control if len(devicesid)",
"working directory # where to find the clientid and secretkey files secpath =",
"from OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration']",
"trackers paired if len(idflarm) == 6: # in case of missing FLR/ICA/OGN (deprecated)",
"\"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu): if (flatil == 0.0): return",
"# print the time for information only if prt: print(\"Hostname:\", hostname) print(\"UTC Time",
"the soaringspota regi = \"reg_NOTYET\" if idflarm == '': idflarm = ognid if",
"(latitude < flatil or latitude > flatiu): return (True) else: # southern hemisfere",
"# nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce = base64.b64encode(os.urandom(36)) # get the",
"url3 = getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") # get the contestants data",
"data from the HAL document return cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype])",
"if 'aircraft_model' in contestants: ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number'",
"# southern hemisfere if (latitude > flatil or latitude < flatiu): return (True)",
"base nonce = base64.b64encode(os.urandom(36)) # get the once base # build the message",
"club = \"club_NOTYET\" if 'aircraft_model' in contestants: ar = contestants['aircraft_model'] else: ar =",
"UTC time local_time = datetime.now() # the local time # print the time",
"case that just the FlarmID and OGN tracker pair idflarm = livetrk[0:9] ognpair",
"get the data from the HAL document return cd def getemb(base, ctype): global",
"authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open the url",
"ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm =",
"import datetime import pycountry from ognddbfuncs import getognreg, getognflarmid from simplehal import HalDocument,",
"prt='no')[0] # get the main data from the contest category = cd['category'] eventname",
"get the main data from the contest category = cd['category'] eventname = cd['name']",
"else: if compcountry != '': nation = compcountry else: nation = \"ES\" #",
"do not have the registration ID on the soaringspota regi = \"reg_NOTYET\" if",
"= contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation =",
"the data from the HAL document return cd def getemb(base, ctype): global apiurl",
"= cl[\"type\"] # search for each class if prt: print(\"Class:\", classname, \"\\n\\n\") #",
"apiurl global auth date = datetime.now() # get the date hostname = socket.gethostname()",
"if (station != \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu): if (flatil",
"parameters =======================# # where to find the SQLITE3 database cwd = os.getcwd() #",
"for each class if prt: print(\"Class:\", classname, \"\\n\\n\") # search for each class",
"cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation",
"prt='no'): global auth # auth and apiurl are globals global apiurl j_obj =",
"if (latitude > flatil or latitude < flatiu): return (True) return(False) ######################################################################## #",
"# # ---------- main code --------------- # # gather the competition data from",
"FlarmID, no piaring if len(livetrk) == 19: # format: FLR123456 OGN654321 # case",
"compcountry else: nation = \"ES\" # by default is SPAIN # convert the",
"cd['country'] # country code - 2 chars code compcountry = country # contry",
"import base64 import os import socket import os.path from datetime import datetime import",
"ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd, 'location') # location data lcname =",
"= {\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes,",
"the contest data, first instance cd = gdata(url1, 'contests', prt='no')[0] # get the",
"# call the fuction that get it # convert to HAL if prt",
"ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\")",
"# ==============================================# utc = datetime.utcnow() # the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") #",
"compcountry != '': nation = compcountry else: nation = \"ES\" # by default",
"assume a Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a ICAO",
"where to store the IGC file # see if index day is requestedd",
"we use API version 1 # ==============================================# utc = datetime.utcnow() # the UTC",
"return (True) return(False) ######################################################################## # get the data from the soaring spot and",
"\"http://api.soaringspot.com/\" # soaringspot API URL rel = \"v1\" # we use API version",
"SoaringSpot and prepaeres the infor for the REAL TIME SCORING # # Author:",
"2021 # #import sys import json import urllib.request import urllib.error import urllib.parse import",
"= contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model' in contestants: ar = contestants['aircraft_model']",
"ognpair = livetrk[10:] # OGN trackers paired if len(idflarm) == 6: # in",
"endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init the number of",
"clientid and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API",
"# get the current working directory # where to find the clientid and",
"from the soaring spot and return it as a HAL document def gdata(url,",
"= ognid if idflarm != '': devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname,",
"HAL document def gdata(url, key, prt='no'): global auth # auth and apiurl are",
"# Build the tracks and turn points, exploring the contestants and task within",
"# print \"CLCLCL\", cl classname = cl[\"type\"] # search for each class if",
"ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd,",
"type else: idflarm = \"OGN\"+idflarm # assume a OGN type # get the",
"current working directory # where to find the clientid and secretkey files secpath",
"OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] #",
"from the HAL document return cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def",
"print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid,",
"== '': idflarm = ognid if idflarm != '': devicesid += idflarm+'/' if",
"classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\":",
"flatil or latitude > flatiu): return (True) else: # southern hemisfere if (latitude",
"> 0): # northern hemisphere if (latitude < flatil or latitude > flatiu):",
"get the UTC time local_time = datetime.now() # the local time # print",
"autho) # build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req)",
"information only print(\"Local Time is now:\", local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36))",
"nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get the initial base of the tree",
"of missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm # assume",
"print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots as a reference and control if",
"# get the flarm if from the OGN DDB ognid = getognflarmid(regi) else:",
"missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm # assume a",
"global apiurl global auth date = datetime.now() # get the date hostname =",
"apiurl+rel # get the contest data, first instance cd = gdata(url1, 'contests', prt='no')[0]",
"(\"URLiauth:\", auth) # get the initial base of the tree url1 = apiurl+rel",
"# by default is SPAIN # convert the 2 chars ID to the",
"data lcname = lc['name'] # location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp",
"= gdata(url1, 'contests', prt='no')[0] # get the main data from the contest category",
"is SPAIN # convert the 2 chars ID to the 3 chars ID",
"'pilot')[0]['nationality'] else: if compcountry != '': nation = compcountry else: nation = \"ES\"",
"HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get the data from the HAL document",
"nation = \"ES\" # by default is SPAIN # convert the 2 chars",
"== 19: # format: FLR123456 OGN654321 # case that just the FlarmID and",
"return (False) if (flatil > 0): # northern hemisphere if (latitude < flatil",
"- May 2021 # #import sys import json import urllib.request import urllib.error import",
"FlarmId from the SoaringSpot livetrk = contestants['live_track_id'] # flarmID and OGN pair if",
"== 6: # in case of missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D':",
"tree url1 = apiurl+rel # get the contest data, first instance cd =",
"in case of missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm",
"Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth # auth and apiurl are globals",
"nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '': nation = compcountry else:",
"compcountry = country # contry as defaults for pilots # convert the 2",
"if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init the number of pilots classes",
"\\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get the initial base of the",
"the main data from the contest category = cd['category'] eventname = cd['name'] compid",
"club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model' in contestants: ar =",
"utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time = datetime.now() # the local time",
"print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category, \"Country\":",
"the tree url1 = apiurl+rel # get the contest data, first instance cd",
"# if we do not have the registration ID on the soaringspota regi",
"pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair =",
"cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar,",
"number of pilots classes = [] pilots = [] devicesid = \"\" #",
"code - 2 chars code compcountry = country # contry as defaults for",
"simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth # auth and",
"data from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global apiurl global auth date",
"print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\",",
"assume a ICAO type else: idflarm = \"OGN\"+idflarm # assume a OGN type",
"len(devicesid) > 0: devicesid = devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\")",
"+ \\ client.encode(encoding='utf-8') # and the message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest()",
"control if len(devicesid) > 0: devicesid = devicesid[0:-1] if prt: print(\"= Pilots ===========================\",",
"utc = datetime.utcnow() # the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the",
"piaring if len(livetrk) == 19: # format: FLR123456 OGN654321 # case that just",
"latitude < flatiu): return (True) return(False) ######################################################################## # get the data from the",
"pycountry from ognddbfuncs import getognreg, getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# #########################################################################",
"=======================# # where to find the SQLITE3 database cwd = os.getcwd() # get",
"SETUP parameters =======================# # where to find the SQLITE3 database cwd = os.getcwd()",
"lcname, \"Country: \", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil",
"pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname,",
"# see if index day is requestedd # --------------------------------------# # ===== SETUP parameters",
"= base64.b64encode(os.urandom(36)) # get the once base # build the message message =",
"def chkfilati(latitude, flatil, flatiu): if (flatil == 0.0): return (False) if (flatil >",
"2 chars code compcountry = country # contry as defaults for pilots #",
"# get the contestants data # print \"CTTCTT\",ctt for contestants in ctt: #",
"\" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\"",
"idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") #",
"document return cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global",
"that daya from SoaringSpot and prepaeres the infor for the REAL TIME SCORING",
"the clientid and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot",
"different classes now within the daya pilots = [] for cl in getemb(cd,",
"for contestants in ctt: # print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name']",
"and prepaeres the infor for the REAL TIME SCORING # # Author: <NAME>",
"the message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) #",
"turn points, exploring the contestants and task within each class # go thru",
"a reference and control if len(devicesid) > 0: devicesid = devicesid[0:-1] if prt:",
"or latitude < flatiu): return (True) return(False) ######################################################################## # get the data from",
"--------------------------------------# # ===== SETUP parameters =======================# # where to find the SQLITE3 database",
"time # print the time for information only if prt: print(\"Hostname:\", hostname) print(\"UTC",
"getemb(cd, 'location') # location data lcname = lc['name'] # location name print(\"\\n\\n= Contest",
"= json.load(r) # convert to JSON return j_obj # return the JSON object",
"= \"reg_NOTYET\" if idflarm == '': idflarm = ognid if idflarm != '':",
"contestants in ctt: # print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname",
"prt: print (\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm = livetrk # case",
"import getognreg, getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global",
"secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL rel = \"v1\"",
"autho): # get the data from the API server req = urllib.request.Request(url) req.add_header('Authorization',",
"ognid) npil += 1 pil = {\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\":",
"!= \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu): if (flatil == 0.0):",
"UTF-8 -*- # This module gets that daya from SoaringSpot and prepaeres the",
"\"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \", country, country, \"End date:\", endate)",
"idfreg, \"OGNpair\", ognpair, ognid) npil += 1 pil = {\"PilotName\": pname, \"Club\": club,",
"= \"\" # Build the tracks and turn points, exploring the contestants and",
"= HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get the data from the HAL",
"getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '': nation =",
"= {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots",
"get the flarm if from the OGN DDB ognid = getognflarmid(regi) else: #",
"get it # convert to HAL if prt == 'yes': # if print",
"auth) # get the initial base of the tree url1 = apiurl+rel #",
"the 2 chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=country) country",
"tracks and turn points, exploring the contestants and task within each class #",
"and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL",
"within each class # go thru the different classes now within the daya",
"ognpair, ognid) npil += 1 pil = {\"PilotName\": pname, \"Club\": club, \"CompID\": cn,",
"Author: <NAME> - May 2021 # #import sys import json import urllib.request import",
"to avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in",
"(\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm = livetrk # case that just",
"= getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") # get the contestants data #",
"from SoaringSpot and prepaeres the infor for the REAL TIME SCORING # #",
"ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### #",
"--------------- # # gather the competition data from SoaringSpot def soa2rts(RTS, client, secretkey,",
"and turn points, exploring the contestants and task within each class # go",
"= compcountry else: nation = \"ES\" # by default is SPAIN # convert",
"fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else:",
"each class url3 = getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") # get the",
"\"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\":",
"===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country:",
"API version 1 # ==============================================# utc = datetime.utcnow() # the UTC time date",
"have the registration ID on the soaringspota regi = \"reg_NOTYET\" if idflarm ==",
"is now:\", utc) print(date) # # print the time for information only print(\"Local",
"classname = cl[\"type\"] # search for each class if prt: print(\"Class:\", classname, \"\\n\\n\")",
"API URL rel = \"v1\" # we use API version 1 # ==============================================#",
"ognid if idflarm != '': devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\",",
"===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\":",
"print the time for information only print(\"Local Time is now:\", local_time) print(\"Config params.",
"built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" '",
"# get the registration from OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in",
"main data from the contest category = cd['category'] eventname = cd['name'] compid =",
"######################################################################## def oksta(station): if (station != \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil,",
"req = urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\",",
"daya pilots = [] for cl in getemb(cd, 'classes'): # print \"CLCLCL\", cl",
"# case that just the FlarmID and OGN tracker pair idflarm = livetrk[0:9]",
"gather the competition data from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global apiurl",
"j_obj # return the JSON object ################################################################### ######################################################################## def oksta(station): if (station !=",
"no piaring if len(livetrk) == 19: # format: FLR123456 OGN654321 # case that",
"the initial base of the tree url1 = apiurl+rel # get the contest",
"getapidata(url, autho): # get the data from the API server req = urllib.request.Request(url)",
"now:\", local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base",
"\"contestants\") ctt = gdata(url3, \"contestants\") # get the contestants data # print \"CTTCTT\",ctt",
"if len(livetrk) == 9: idflarm = livetrk # case that just the FlarmID,",
"time for information only print(\"Local Time is now:\", local_time) print(\"Config params. SECpath:\", secpath)",
"# # gather the competition data from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False):",
"= contestants['live_track_id'] # flarmID and OGN pair if prt: print (\"Live_track:\", livetrk) if",
"each class # go thru the different classes now within the daya pilots",
"hmac import hashlib import base64 import os import socket import os.path from datetime",
"use API version 1 # ==============================================# utc = datetime.utcnow() # the UTC time",
"cl[\"type\"] # search for each class if prt: print(\"Class:\", classname, \"\\n\\n\") # search",
"May 2021 # #import sys import json import urllib.request import urllib.error import urllib.parse",
"utc) print(date) # # print the time for information only print(\"Local Time is",
"\"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\":",
"print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname,",
"for the REAL TIME SCORING # # Author: <NAME> - May 2021 #",
"= pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair",
"date hostname = socket.gethostname() # directory where to store the IGC file #",
"print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] #",
"endate = cd['end_date'] lc = getemb(cd, 'location') # location data lcname = lc['name']",
"auth and apiurl are globals ######################################################################### def getapidata(url, autho): # get the data",
"'classes'): # print \"CLCLCL\", cl classname = cl[\"type\"] # search for each class",
"# convert it to utf8 in order to avoid problems pname = fname.encode('utf-8').decode('utf-8')",
"\"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil +=",
"HAL document return cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype):",
"on each class url3 = getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") # get",
"\"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid)",
"= cd['country'] # country code - 2 chars code compcountry = country #",
"+ \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get the",
"\"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\")",
"is now:\", local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once",
"idflarm == '': idflarm = ognid if idflarm != '': devicesid += idflarm+'/'",
"the SoaringSpot livetrk = contestants['live_track_id'] # flarmID and OGN pair if prt: print",
"message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the message digest digest =",
"name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \", country, country, \"End",
"country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair}",
"contestants: ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number' in contestants: cn",
"'contestant_number' in contestants: cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality' in",
"\"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\":",
"regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil += 1",
"avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants:",
"classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots as a",
"# init the number of pilots classes = [] pilots = [] devicesid",
"global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # #",
"server req = urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization header req.add_header(\"Accept\", \"application/json\")",
") # build the digital signature # the AUTHORIZATION ID is built now",
"= 0 # init the number of pilots classes = [] pilots =",
"# check if we have the FlarmId from the SoaringSpot livetrk = contestants['live_track_id']",
"if idflarm == '': idflarm = ognid if idflarm != '': devicesid +=",
"= getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\" ognid = \"\" idfreg",
"and apiurl are globals ######################################################################### def getapidata(url, autho): # get the data from",
"livetrk # case that just the FlarmID, no piaring if len(livetrk) == 19:",
"eventname = cd['name'] compid = cd['id'] country = cd['country'] # country code -",
"global auth date = datetime.now() # get the date hostname = socket.gethostname() #",
"the FlarmID and OGN tracker pair idflarm = livetrk[0:9] ognpair = livetrk[10:] #",
"hostname) print(\"UTC Time is now:\", utc) print(date) # # print the time for",
"the number of pilots as a reference and control if len(devicesid) > 0:",
"directory where to store the IGC file # see if index day is",
"the once base nonce = base64.b64encode(os.urandom(36)) # get the once base # build",
"# search for each class if prt: print(\"Class:\", classname, \"\\n\\n\") # search for",
"# where to find the clientid and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl",
"contestants and task within each class # go thru the different classes now",
"# This module gets that daya from SoaringSpot and prepaeres the infor for",
"os.path from datetime import datetime import pycountry from ognddbfuncs import getognreg, getognflarmid from",
"# # print the time for information only print(\"Local Time is now:\", local_time)",
"= datetime.now() # the local time # print the time for information only",
"getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ###################################################################",
"\"contestants\") # get the contestants data # print \"CTTCTT\",ctt for contestants in ctt:",
"= ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd, 'location') # location data lcname",
"pil = {\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\":",
"nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\",",
"flatiu): if (flatil == 0.0): return (False) if (flatil > 0): # northern",
"prt == 'yes': # if print is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python(",
"# location data lcname = lc['name'] # location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\",",
"globals ######################################################################### def getapidata(url, autho): # get the data from the API server",
"def gdata(url, key, prt='no'): global auth # auth and apiurl are globals global",
"of pilots as a reference and control if len(devicesid) > 0: devicesid =",
"chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm",
"return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main",
"= getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8 in order to avoid problems",
"# where to find the SQLITE3 database cwd = os.getcwd() # get the",
"#-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth # auth and apiurl are globals #########################################################################",
"day is requestedd # --------------------------------------# # ===== SETUP parameters =======================# # where to",
"the fuction that get it # convert to HAL if prt == 'yes':",
"\"v1\" # we use API version 1 # ==============================================# utc = datetime.utcnow() #",
"get the data from the API server req = urllib.request.Request(url) req.add_header('Authorization', autho) #",
"= nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the message digest digest = hmac.new(secretkey,",
"the SQLITE3 database cwd = os.getcwd() # get the current working directory #",
"flarm if from the OGN DDB ognid = getognflarmid(regi) else: # if we",
"contestants on each class url3 = getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") #",
"\"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil += 1 pil",
"country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes, \"Pilots\": pilots, \"Devices\": devicesid} return (RTS)",
"# open the url resource j_obj = json.load(r) # convert to JSON return",
"\"ES\" # by default is SPAIN # convert the 2 chars ID to",
"#!/usr/bin/python3 # -*- coding: UTF-8 -*- # This module gets that daya from",
"country = cd['country'] # country code - 2 chars code compcountry = country",
"the infor for the REAL TIME SCORING # # Author: <NAME> - May",
"search for each class # search for the contestants on each class url3",
"getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8 in order",
"This module gets that daya from SoaringSpot and prepaeres the infor for the",
"= utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time = datetime.now() # the local",
"if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model'",
"ar = \"am_NOTYET\" if 'contestant_number' in contestants: cn = contestants['contestant_number'] else: cn =",
"or latitude > flatiu): return (True) else: # southern hemisfere if (latitude >",
"auth and apiurl are globals global apiurl j_obj = getapidata(url, auth) # call",
"competition data from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global apiurl global auth",
"j_obj), apiurl+'rel/' + key) # get the data from the HAL document return",
"idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\",",
"regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll",
"points, exploring the contestants and task within each class # go thru the",
"getognreg, getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth",
"build the message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the message",
"contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number' in contestants: cn = contestants['contestant_number'] else:",
"convert it to utf8 in order to avoid problems pname = fname.encode('utf-8').decode('utf-8') +",
"= \"am_NOTYET\" if 'contestant_number' in contestants: cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\"",
"apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL rel = \"v1\" # we use",
"idflarm = \"\" ognpair = \"\" ognid = \"\" idfreg = \"\" if",
"global auth # auth and apiurl are globals ######################################################################### def getapidata(url, autho): #",
"# assume a OGN type # get the registration from OGN DDB idfreg",
"devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation,",
"import hashlib import base64 import os import socket import os.path from datetime import",
"number of pilots as a reference and control if len(devicesid) > 0: devicesid",
"as a reference and control if len(devicesid) > 0: devicesid = devicesid[0:-1] if",
"in contestants: # check if we have the FlarmId from the SoaringSpot livetrk",
"the data from the API server req = urllib.request.Request(url) req.add_header('Authorization', autho) # build",
"# and the message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode()",
"else: cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality']",
"Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\",",
"and the message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() )",
"print the time for information only if prt: print(\"Hostname:\", hostname) print(\"UTC Time is",
"\"ICA\"+idflarm # assume a ICAO type else: idflarm = \"OGN\"+idflarm # assume a",
"ognid = getognflarmid(regi) else: # if we do not have the registration ID",
"SQLITE3 database cwd = os.getcwd() # get the current working directory # where",
"get the contestants data # print \"CTTCTT\",ctt for contestants in ctt: # print",
"the competition data from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global apiurl global",
"problems pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club",
"== 'yes': # if print is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj),",
"livetrk = contestants['live_track_id'] # flarmID and OGN pair if prt: print (\"Live_track:\", livetrk)",
"\"am_NOTYET\" if 'contestant_number' in contestants: cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\" if",
"datetime.now() # get the date hostname = socket.gethostname() # directory where to store",
"'contests', prt='no')[0] # get the main data from the contest category = cd['category']",
"contestants: # check if we have the FlarmId from the SoaringSpot livetrk =",
"lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8 in order to avoid",
"get the data from the soaring spot and return it as a HAL",
"cl classname = cl[\"type\"] # search for each class if prt: print(\"Class:\", classname,",
"getemb(cd, 'classes'): # print \"CLCLCL\", cl classname = cl[\"type\"] # search for each",
"print(\"Local Time is now:\", local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get",
"\"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if",
"case of missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm #",
"= urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\")",
"each class if prt: print(\"Class:\", classname, \"\\n\\n\") # search for each class #",
"\"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes, \"Pilots\": pilots, \"Devices\": devicesid} return",
"= [] pilots = [] devicesid = \"\" # Build the tracks and",
"return cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl",
"# get the date hostname = socket.gethostname() # directory where to store the",
"FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm # assume a Flarm",
"if len(idflarm) == 6: # in case of missing FLR/ICA/OGN (deprecated) if idflarm[0]",
"cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL rel = \"v1\" # we",
"global auth # auth and apiurl are globals global apiurl j_obj = getapidata(url,",
"required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get the",
"nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce = base64.b64encode(os.urandom(36)) # get the once",
"JSON return j_obj # return the JSON object ################################################################### ######################################################################## def oksta(station): if",
"base of the tree url1 = apiurl+rel # get the contest data, first",
"# print \"CTTCTT\",ctt for contestants in ctt: # print \"FT\", ft, \"\\n\\n\" fname",
"a HAL document def gdata(url, key, prt='no'): global auth # auth and apiurl",
"pilots = [] for cl in getemb(cd, 'classes'): # print \"CLCLCL\", cl classname",
"(base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code --------------- # # gather the competition",
"find the SQLITE3 database cwd = os.getcwd() # get the current working directory",
"chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3",
"= datetime.now() # get the date hostname = socket.gethostname() # directory where to",
"in ctt: # print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname =",
"ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid",
"hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build the digital signature #",
"daya from SoaringSpot and prepaeres the infor for the REAL TIME SCORING #",
"country code - 2 chars code compcountry = country # contry as defaults",
"len(livetrk) == 19: # format: FLR123456 OGN654321 # case that just the FlarmID",
"contest data, first instance cd = gdata(url1, 'contests', prt='no')[0] # get the main",
"= \"OGN\"+idflarm # assume a OGN type # get the registration from OGN",
"northern hemisphere if (latitude < flatil or latitude > flatiu): return (True) else:",
"apiurl j_obj = getapidata(url, auth) # call the fuction that get it #",
"idflarm[0] == 'D': idflarm = \"FLR\"+idflarm # assume a Flarm type elif idflarm[0].isdigit():",
"time for information only if prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc)",
"######################################################################## # get the data from the soaring spot and return it as",
"the AUTHORIZATION ID is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"'",
"UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time = datetime.now()",
"= cd['id'] country = cd['country'] # country code - 2 chars code compcountry",
"################################################################### ######################################################################## def oksta(station): if (station != \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude,",
"ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate",
"# convert to JSON return j_obj # return the JSON object ################################################################### ########################################################################",
"(True) return(False) ######################################################################## # get the data from the soaring spot and return",
"where to find the clientid and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl =",
"not have the registration ID on the soaringspota regi = \"reg_NOTYET\" if idflarm",
"index day is requestedd # --------------------------------------# # ===== SETUP parameters =======================# # where",
"urllib.parse import hmac import hashlib import base64 import os import socket import os.path",
"registration from OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi =",
"(latitude > flatil or latitude < flatiu): return (True) return(False) ######################################################################## # get",
"prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\",",
"prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init the number of pilots classes =",
"task within each class # go thru the different classes now within the",
"# the local time # print the time for information only if prt:",
"search for each class if prt: print(\"Class:\", classname, \"\\n\\n\") # search for each",
"the current working directory # where to find the clientid and secretkey files",
"return it as a HAL document def gdata(url, key, prt='no'): global auth #",
"getapidata(url, auth) # call the fuction that get it # convert to HAL",
"the FlarmId from the SoaringSpot livetrk = contestants['live_track_id'] # flarmID and OGN pair",
"# Author: <NAME> - May 2021 # #import sys import json import urllib.request",
"npil += 1 pil = {\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation,",
"once base nonce = base64.b64encode(os.urandom(36)) # get the once base # build the",
"# print the time for information only print(\"Local Time is now:\", local_time) print(\"Config",
"to the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid =",
"of pilots classes = [] pilots = [] devicesid = \"\" # Build",
"ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\" ognid =",
"= getognflarmid(regi) else: # if we do not have the registration ID on",
"RTS = {\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\":",
"the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open the",
"soa2rts(RTS, client, secretkey, prt=False): global apiurl global auth date = datetime.now() # get",
"\"\" ognid = \"\" idfreg = \"\" if 'live_track_id' in contestants: # check",
"livetrk[0:9] ognpair = livetrk[10:] # OGN trackers paired if len(idflarm) == 6: #",
"auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\",",
"6: # in case of missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm",
"ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if prt:",
"print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce =",
"= cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL rel = \"v1\" #",
"print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get the data",
"ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code --------------- #",
"\"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes, \"Pilots\": pilots, \"Devices\":",
"\"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print",
"FlarmID and OGN tracker pair idflarm = livetrk[0:9] ognpair = livetrk[10:] # OGN",
"country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\"",
"# build the digital signature # the AUTHORIZATION ID is built now auth",
"def oksta(station): if (station != \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu):",
"\"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it to",
"# gather the competition data from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global",
"auth # auth and apiurl are globals ######################################################################### def getapidata(url, autho): # get",
"==============================================# utc = datetime.utcnow() # the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get",
"check if we have the FlarmId from the SoaringSpot livetrk = contestants['live_track_id'] #",
"Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a ICAO type else:",
"import json import urllib.request import urllib.error import urllib.parse import hmac import hashlib import",
"HAL if prt == 'yes': # if print is required print(json.dumps(j_obj, indent=4)) cd",
"where to find the SQLITE3 database cwd = os.getcwd() # get the current",
"# #import sys import json import urllib.request import urllib.error import urllib.parse import hmac",
"class # go thru the different classes now within the daya pilots =",
"for the contestants on each class url3 = getlinks(cl, \"contestants\") ctt = gdata(url3,",
"getlinks(cl, \"contestants\") ctt = gdata(url3, \"contestants\") # get the contestants data # print",
"hashlib import base64 import os import socket import os.path from datetime import datetime",
"igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll)",
"<NAME> - May 2021 # #import sys import json import urllib.request import urllib.error",
"# get the once base # build the message message = nonce+date.encode(encoding='utf-8') +",
"# search for the contestants on each class url3 = getlinks(cl, \"contestants\") ctt",
"pair if prt: print (\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm = livetrk",
"find the clientid and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" #",
"ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil += 1 pil =",
"len(idflarm) == 6: # in case of missing FLR/ICA/OGN (deprecated) if idflarm[0] ==",
"# auth and apiurl are globals global apiurl j_obj = getapidata(url, auth) #",
"SPAIN # convert the 2 chars ID to the 3 chars ID ccc",
"we have the FlarmId from the SoaringSpot livetrk = contestants['live_track_id'] # flarmID and",
"if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots as a reference and",
"print(\"Class:\", classname, \"\\n\\n\") # search for each class # search for the contestants",
"contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants,",
"just the FlarmID, no piaring if len(livetrk) == 19: # format: FLR123456 OGN654321",
"data, first instance cd = gdata(url1, 'contests', prt='no')[0] # get the main data",
"2 chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 =",
"for information only print(\"Local Time is now:\", local_time) print(\"Config params. SECpath:\", secpath) #",
"\"\" if 'live_track_id' in contestants: # check if we have the FlarmId from",
"to JSON return j_obj # return the JSON object ################################################################### ######################################################################## def oksta(station):",
"!= '': nation = compcountry else: nation = \"ES\" # by default is",
"flatil, flatiu): if (flatil == 0.0): return (False) if (flatil > 0): #",
"devicesid = devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS =",
"if idflarm != '': devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club,",
"JSON object ################################################################### ######################################################################## def oksta(station): if (station != \"FLYMASTER\"): return(True) return(False) #####################",
"from ognddbfuncs import getognreg, getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global",
"classes now within the daya pilots = [] for cl in getemb(cd, 'classes'):",
"go thru the different classes now within the daya pilots = [] for",
"for each class # search for the contestants on each class url3 =",
"= \"http://api.soaringspot.com/\" # soaringspot API URL rel = \"v1\" # we use API",
"= os.getcwd() # get the current working directory # where to find the",
"'': devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\",",
"only print(\"Local Time is now:\", local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) #",
"req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open the url resource j_obj",
"category = cd['category'] eventname = cd['name'] compid = cd['id'] country = cd['country'] #",
"= \"\" ognpair = \"\" ognid = \"\" idfreg = \"\" if 'live_track_id'",
"prt: print(\"Class:\", classname, \"\\n\\n\") # search for each class # search for the",
"nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm,",
"idflarm = \"OGN\"+idflarm # assume a OGN type # get the registration from",
"'D': idflarm = \"FLR\"+idflarm # assume a Flarm type elif idflarm[0].isdigit(): idflarm =",
"import urllib.error import urllib.parse import hmac import hashlib import base64 import os import",
"get the initial base of the tree url1 = apiurl+rel # get the",
"each class # search for the contestants on each class url3 = getlinks(cl,",
"= contestants['aircraft_registration'] # get the flarm if from the OGN DDB ognid =",
"\"club_NOTYET\" if 'aircraft_model' in contestants: ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\" if",
"see if index day is requestedd # --------------------------------------# # ===== SETUP parameters =======================#",
"\"\" # Build the tracks and turn points, exploring the contestants and task",
"'pilot')[0]['last_name'] # convert it to utf8 in order to avoid problems pname =",
"getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '': nation = compcountry else: nation =",
"= \"\" if 'live_track_id' in contestants: # check if we have the FlarmId",
"'live_track_id' in contestants: # check if we have the FlarmId from the SoaringSpot",
"ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd, 'location')",
"if prt: print (\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm = livetrk #",
"if we do not have the registration ID on the soaringspota regi =",
"\"OGNpair\", ognpair, ognid) npil += 1 pil = {\"PilotName\": pname, \"Club\": club, \"CompID\":",
"\"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert",
"client, secretkey, prt=False): global apiurl global auth date = datetime.now() # get the",
"prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc) print(date) # # print the",
"signature = str(base64.b64encode(digest).decode() ) # build the digital signature # the AUTHORIZATION ID",
"'location') # location data lcname = lc['name'] # location name print(\"\\n\\n= Contest ===============================\")",
"idflarm = ognid if idflarm != '': devicesid += idflarm+'/' if prt: print(\"Pilot:\",",
"= \"club_NOTYET\" if 'aircraft_model' in contestants: ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\"",
"for pilots # convert the 2 chars ID to the 3 chars ID",
"\"\\n\\n\") # search for each class # search for the contestants on each",
"= \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if",
"local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce",
"\"OGN\"+idflarm # assume a OGN type # get the registration from OGN DDB",
"\", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0",
"if len(livetrk) == 19: # format: FLR123456 OGN654321 # case that just the",
"SCORING # # Author: <NAME> - May 2021 # #import sys import json",
"str(base64.b64encode(digest).decode() ) # build the digital signature # the AUTHORIZATION ID is built",
"\"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init the",
"= ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\" ognid",
"ognpair = \"\" ognid = \"\" idfreg = \"\" if 'live_track_id' in contestants:",
"order to avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club'",
"r = urllib.request.urlopen(req) # open the url resource j_obj = json.load(r) # convert",
"by default is SPAIN # convert the 2 chars ID to the 3",
"idflarm != '': devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\",",
"prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category,",
"\\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get the initial",
"to store the IGC file # see if index day is requestedd #",
"for information only if prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc) print(date)",
"in getemb(cd, 'classes'): # print \"CLCLCL\", cl classname = cl[\"type\"] # search for",
"auth) # call the fuction that get it # convert to HAL if",
"else: nation = \"ES\" # by default is SPAIN # convert the 2",
"\"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\":",
"fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8",
"'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8 in order to",
"getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code ---------------",
"\\ client.encode(encoding='utf-8') # and the message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature",
"category, \"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \", country,",
"spot and return it as a HAL document def gdata(url, key, prt='no'): global",
"params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce = base64.b64encode(os.urandom(36))",
"pilots # convert the 2 chars ID to the 3 chars ID ccc",
"REAL TIME SCORING # # Author: <NAME> - May 2021 # #import sys",
"from datetime import datetime import pycountry from ognddbfuncs import getognreg, getognflarmid from simplehal",
"digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build the digital",
"\"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi,",
"country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair,",
"\"Registration\": regi, \"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil)",
"as defaults for pilots # convert the 2 chars ID to the 3",
"\"application/hal+json\") r = urllib.request.urlopen(req) # open the url resource j_obj = json.load(r) #",
"(flatil == 0.0): return (False) if (flatil > 0): # northern hemisphere if",
"= gdata(url3, \"contestants\") # get the contestants data # print \"CTTCTT\",ctt for contestants",
"chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3",
"lc['name'] # location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp",
"# we use API version 1 # ==============================================# utc = datetime.utcnow() # the",
"and control if len(devicesid) > 0: devicesid = devicesid[0:-1] if prt: print(\"= Pilots",
"# directory where to store the IGC file # see if index day",
"of the tree url1 = apiurl+rel # get the contest data, first instance",
"== 'D': idflarm = \"FLR\"+idflarm # assume a Flarm type elif idflarm[0].isdigit(): idflarm",
"utf8 in order to avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8')",
"for cl in getemb(cd, 'classes'): # print \"CLCLCL\", cl classname = cl[\"type\"] #",
"+ \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club",
"json import urllib.request import urllib.error import urllib.parse import hmac import hashlib import base64",
"hemisfere if (latitude > flatil or latitude < flatiu): return (True) return(False) ########################################################################",
"paired if len(idflarm) == 6: # in case of missing FLR/ICA/OGN (deprecated) if",
"j_obj = getapidata(url, auth) # call the fuction that get it # convert",
"# location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\",",
"# search for each class # search for the contestants on each class",
"pilots as a reference and control if len(devicesid) > 0: devicesid = devicesid[0:-1]",
"---------- main code --------------- # # gather the competition data from SoaringSpot def",
"it as a HAL document def gdata(url, key, prt='no'): global auth # auth",
"# contry as defaults for pilots # convert the 2 chars ID to",
"# the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time",
"-*- coding: UTF-8 -*- # This module gets that daya from SoaringSpot and",
"print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \",",
"0 # init the number of pilots classes = [] pilots = []",
"print \"CLCLCL\", cl classname = cl[\"type\"] # search for each class if prt:",
"(True) else: # southern hemisfere if (latitude > flatil or latitude < flatiu):",
"date = datetime.now() # get the date hostname = socket.gethostname() # directory where",
"print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc) print(date) # # print the time",
"\"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil += 1 pil = {\"PilotName\": pname, \"Club\":",
"# build the message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the",
"'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\" ognid = \"\" idfreg = \"\"",
"'aircraft_model' in contestants: ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number' in",
"only if prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc) print(date) # #",
"prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots as a reference and control",
"flatiu): return (True) else: # southern hemisfere if (latitude > flatil or latitude",
"header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open the url resource",
"if compcountry != '': nation = compcountry else: nation = \"ES\" # by",
"= [] devicesid = \"\" # Build the tracks and turn points, exploring",
"url resource j_obj = json.load(r) # convert to JSON return j_obj # return",
"socket.gethostname() # directory where to store the IGC file # see if index",
"classname, \"\\n\\n\") # search for each class # search for the contestants on",
"in order to avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if",
"data from the soaring spot and return it as a HAL document def",
"# ===== SETUP parameters =======================# # where to find the SQLITE3 database cwd",
"cll = {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of",
"ctt = gdata(url3, \"contestants\") # get the contestants data # print \"CTTCTT\",ctt for",
"case that just the FlarmID, no piaring if len(livetrk) == 19: # format:",
"local_time = datetime.now() # the local time # print the time for information",
"it to utf8 in order to avoid problems pname = fname.encode('utf-8').decode('utf-8') + \\",
"date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time = datetime.now() # the",
"chkfilati(latitude, flatil, flatiu): if (flatil == 0.0): return (False) if (flatil > 0):",
"return the JSON object ################################################################### ######################################################################## def oksta(station): if (station != \"FLYMASTER\"): return(True)",
"= getapidata(url, auth) # call the fuction that get it # convert to",
"is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\"",
"soaring spot and return it as a HAL document def gdata(url, key, prt='no'):",
"< flatiu): return (True) return(False) ######################################################################## # get the data from the soaring",
"build the digital signature # the AUTHORIZATION ID is built now auth =",
"location data lcname = lc['name'] # location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category,",
"the time for information only print(\"Local Time is now:\", local_time) print(\"Config params. SECpath:\",",
"have the FlarmId from the SoaringSpot livetrk = contestants['live_track_id'] # flarmID and OGN",
"gdata(url, key, prt='no'): global auth # auth and apiurl are globals global apiurl",
"return (True) else: # southern hemisfere if (latitude > flatil or latitude <",
"= \"v1\" # we use API version 1 # ==============================================# utc = datetime.utcnow()",
"location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\", compid)",
"> flatiu): return (True) else: # southern hemisfere if (latitude > flatil or",
"the 2 chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3",
"\"Country: \", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil =",
"are globals global apiurl j_obj = getapidata(url, auth) # call the fuction that",
"auth date = datetime.now() # get the date hostname = socket.gethostname() # directory",
"= pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd, 'location') #",
"if we have the FlarmId from the SoaringSpot livetrk = contestants['live_track_id'] # flarmID",
"= livetrk[0:9] ognpair = livetrk[10:] # OGN trackers paired if len(idflarm) == 6:",
"= devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\":",
"= apiurl+rel # get the contest data, first instance cd = gdata(url1, 'contests',",
"OGN654321 # case that just the FlarmID and OGN tracker pair idflarm =",
"the date hostname = socket.gethostname() # directory where to store the IGC file",
"devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname,",
"datetime import pycountry from ognddbfuncs import getognreg, getognflarmid from simplehal import HalDocument, Resolver",
"> 0: devicesid = devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid)",
"signature # the AUTHORIZATION ID is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' +",
"as a HAL document def gdata(url, key, prt='no'): global auth # auth and",
"the UTC time local_time = datetime.now() # the local time # print the",
"ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it",
"# get the data from the API server req = urllib.request.Request(url) req.add_header('Authorization', autho)",
"'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] # get the flarm if from the",
"global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code --------------- # #",
"to find the clientid and secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\"",
"exploring the contestants and task within each class # go thru the different",
"now within the daya pilots = [] for cl in getemb(cd, 'classes'): #",
"ar = contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number' in contestants: cn =",
"cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get the data from the",
"database cwd = os.getcwd() # get the current working directory # where to",
"in contestants: regi = contestants['aircraft_registration'] # get the flarm if from the OGN",
"\"\" ognpair = \"\" ognid = \"\" idfreg = \"\" if 'live_track_id' in",
"contest category = cd['category'] eventname = cd['name'] compid = cd['id'] country = cd['country']",
"# format: FLR123456 OGN654321 # case that just the FlarmID and OGN tracker",
"ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the",
"# if print is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' +",
"livetrk[10:] # OGN trackers paired if len(idflarm) == 6: # in case of",
"module gets that daya from SoaringSpot and prepaeres the infor for the REAL",
"if prt == 'yes': # if print is required print(json.dumps(j_obj, indent=4)) cd =",
"datetime.utcnow() # the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time",
"digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build the digital signature # the AUTHORIZATION",
"# -*- coding: UTF-8 -*- # This module gets that daya from SoaringSpot",
"first instance cd = gdata(url1, 'contests', prt='no')[0] # get the main data from",
"os import socket import os.path from datetime import datetime import pycountry from ognddbfuncs",
"- 2 chars code compcountry = country # contry as defaults for pilots",
"######################################################################### global apiurl global auth # auth and apiurl are globals ######################################################################### def",
"if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] # get the flarm if from",
"print(date) # # print the time for information only print(\"Local Time is now:\",",
"= str(base64.b64encode(digest).decode() ) # build the digital signature # the AUTHORIZATION ID is",
"= cd['end_date'] lc = getemb(cd, 'location') # location data lcname = lc['name'] #",
"and return it as a HAL document def gdata(url, key, prt='no'): global auth",
"#import sys import json import urllib.request import urllib.error import urllib.parse import hmac import",
"pilots classes = [] pilots = [] devicesid = \"\" # Build the",
"the registration ID on the soaringspota regi = \"reg_NOTYET\" if idflarm == '':",
"on the soaringspota regi = \"reg_NOTYET\" if idflarm == '': idflarm = ognid",
"gets that daya from SoaringSpot and prepaeres the infor for the REAL TIME",
"getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth #",
"> flatil or latitude < flatiu): return (True) return(False) ######################################################################## # get the",
"Time is now:\", local_time) print(\"Config params. SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the",
"open the url resource j_obj = json.load(r) # convert to JSON return j_obj",
"from SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global apiurl global auth date =",
"the tracks and turn points, exploring the contestants and task within each class",
"# case that just the FlarmID, no piaring if len(livetrk) == 19: #",
"from the API server req = urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization",
"tracker pair idflarm = livetrk[0:9] ognpair = livetrk[10:] # OGN trackers paired if",
"type # get the registration from OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration'",
"the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC time local_time =",
"and task within each class # go thru the different classes now within",
"if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3,",
"0): # northern hemisphere if (latitude < flatil or latitude > flatiu): return",
"flatiu): return (True) return(False) ######################################################################## # get the data from the soaring spot",
"if print is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key)",
"the once base # build the message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8')",
"if (flatil == 0.0): return (False) if (flatil > 0): # northern hemisphere",
"time local_time = datetime.now() # the local time # print the time for",
"the time for information only if prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\",",
"+ \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get the initial base of",
"fuction that get it # convert to HAL if prt == 'yes': #",
"{\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\":",
"'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '': nation = compcountry",
"just the FlarmID and OGN tracker pair idflarm = livetrk[0:9] ognpair = livetrk[10:]",
"# get the main data from the contest category = cd['category'] eventname =",
"return j_obj # return the JSON object ################################################################### ######################################################################## def oksta(station): if (station",
"indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get the data from",
"pname = fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club =",
"resource j_obj = json.load(r) # convert to JSON return j_obj # return the",
"secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce = base64.b64encode(os.urandom(36)) # get",
"ognid = \"\" idfreg = \"\" if 'live_track_id' in contestants: # check if",
"SECpath:\", secpath) # nonce=base64.b64encode(OpenSSL.rand.bytes(36)) # get the once base nonce = base64.b64encode(os.urandom(36)) #",
"club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\",",
"code compcountry = country # contry as defaults for pilots # convert the",
"lc = getemb(cd, 'location') # location data lcname = lc['name'] # location name",
"digital signature # the AUTHORIZATION ID is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"'",
"the different classes now within the daya pilots = [] for cl in",
"cwd = os.getcwd() # get the current working directory # where to find",
"igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil",
"contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model' in contestants: ar = contestants['aircraft_model'] else:",
"print the number of pilots as a reference and control if len(devicesid) >",
"if prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc) print(date) # # print",
"= \"\" ognid = \"\" idfreg = \"\" if 'live_track_id' in contestants: #",
"# ---------- main code --------------- # # gather the competition data from SoaringSpot",
"datetime.now() # the local time # print the time for information only if",
"'': nation = compcountry else: nation = \"ES\" # by default is SPAIN",
"the flarm if from the OGN DDB ognid = getognflarmid(regi) else: # if",
"!= '': devicesid += idflarm+'/' if prt: print(\"Pilot:\", pname, \"Club:\", club, \"CompID:\", cn,",
"' #print (\"URLiauth:\", auth) # get the initial base of the tree url1",
"if 'contestant_number' in contestants: cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality'",
"return(False) ######################################################################## # get the data from the soaring spot and return it",
"hostname = socket.gethostname() # directory where to store the IGC file # see",
"a Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a ICAO type",
"#print (\"URLiauth:\", auth) # get the initial base of the tree url1 =",
"idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] # get the",
"= datetime.utcnow() # the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\") # get the UTC",
"country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init",
"the FlarmID, no piaring if len(livetrk) == 19: # format: FLR123456 OGN654321 #",
"country = ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd, 'location') # location data",
"country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 #",
"cd['category'] eventname = cd['name'] compid = cd['id'] country = cd['country'] # country code",
"HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth # auth and apiurl are",
"socket import os.path from datetime import datetime import pycountry from ognddbfuncs import getognreg,",
"= cd['name'] compid = cd['id'] country = cd['country'] # country code - 2",
"if prt: print(\"Class:\", classname, \"\\n\\n\") # search for each class # search for",
"country # contry as defaults for pilots # convert the 2 chars ID",
"AUTHORIZATION ID is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' +",
"message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build",
"OGN trackers paired if len(idflarm) == 6: # in case of missing FLR/ICA/OGN",
"classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number of pilots as a reference",
"the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants,",
"key, prt='no'): global auth # auth and apiurl are globals global apiurl j_obj",
"# get the contest data, first instance cd = gdata(url1, 'contests', prt='no')[0] #",
"= livetrk # case that just the FlarmID, no piaring if len(livetrk) ==",
"a ICAO type else: idflarm = \"OGN\"+idflarm # assume a OGN type #",
"auth # auth and apiurl are globals global apiurl j_obj = getapidata(url, auth)",
"call the fuction that get it # convert to HAL if prt ==",
"soaringspot API URL rel = \"v1\" # we use API version 1 #",
"a OGN type # get the registration from OGN DDB idfreg = getognreg(idflarm[3:9])",
"cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\",",
"len(livetrk) == 9: idflarm = livetrk # case that just the FlarmID, no",
"def getapidata(url, autho): # get the data from the API server req =",
"base # build the message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and",
"# get the data from the HAL document return cd def getemb(base, ctype):",
"\"Flarm:\", idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil += 1 pil = {\"PilotName\":",
"date:\", endate) print(\"=========================================\\n\\n\") if prt: print(\"Classes:\\n========\\n\\n\") npil = 0 # init the number",
"os.getcwd() # get the current working directory # where to find the clientid",
"cd = gdata(url1, 'contests', prt='no')[0] # get the main data from the contest",
"if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm # assume a Flarm type elif",
"cd['end_date'] lc = getemb(cd, 'location') # location data lcname = lc['name'] # location",
"secretkey, prt=False): global apiurl global auth date = datetime.now() # get the date",
"idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a ICAO type else: idflarm = \"OGN\"+idflarm",
"= [] for cl in getemb(cd, 'classes'): # print \"CLCLCL\", cl classname =",
"devicesid = \"\" # Build the tracks and turn points, exploring the contestants",
"== 0.0): return (False) if (flatil > 0): # northern hemisphere if (latitude",
"global apiurl global auth # auth and apiurl are globals ######################################################################### def getapidata(url,",
"infor for the REAL TIME SCORING # # Author: <NAME> - May 2021",
"ctt: # print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants,",
"if from the OGN DDB ognid = getognflarmid(regi) else: # if we do",
"j_obj = json.load(r) # convert to JSON return j_obj # return the JSON",
"apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) #",
"# go thru the different classes now within the daya pilots = []",
"urllib.error import urllib.parse import hmac import hashlib import base64 import os import socket",
"# flarmID and OGN pair if prt: print (\"Live_track:\", livetrk) if len(livetrk) ==",
"gdata(url3, \"contestants\") # get the contestants data # print \"CTTCTT\",ctt for contestants in",
"DDB ognid = getognflarmid(regi) else: # if we do not have the registration",
"'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '':",
"from the SoaringSpot livetrk = contestants['live_track_id'] # flarmID and OGN pair if prt:",
"init the number of pilots classes = [] pilots = [] devicesid =",
"# build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) #",
"convert the 2 chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=nation)",
"pair idflarm = livetrk[0:9] ognpair = livetrk[10:] # OGN trackers paired if len(idflarm)",
"= \"ES\" # by default is SPAIN # convert the 2 chars ID",
"object ################################################################### ######################################################################## def oksta(station): if (station != \"FLYMASTER\"): return(True) return(False) ##################### def",
"pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if prt: print(\"----------------------------------------------------------------\\n\\n\") # print the number",
"the JSON object ################################################################### ######################################################################## def oksta(station): if (station != \"FLYMASTER\"): return(True) return(False)",
"data from the contest category = cd['category'] eventname = cd['name'] compid = cd['id']",
"# northern hemisphere if (latitude < flatil or latitude > flatiu): return (True)",
"in contestants: cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants,",
"import hmac import hashlib import base64 import os import socket import os.path from",
"# return the JSON object ################################################################### ######################################################################## def oksta(station): if (station != \"FLYMASTER\"):",
"the 3 chars ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date']",
"flarmID and OGN pair if prt: print (\"Live_track:\", livetrk) if len(livetrk) == 9:",
"3 chars ID ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id']",
"import os import socket import os.path from datetime import datetime import pycountry from",
"it # convert to HAL if prt == 'yes': # if print is",
"files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL rel =",
"= contestants['aircraft_model'] else: ar = \"am_NOTYET\" if 'contestant_number' in contestants: cn = contestants['contestant_number']",
"# assume a ICAO type else: idflarm = \"OGN\"+idflarm # assume a OGN",
"and apiurl are globals global apiurl j_obj = getapidata(url, auth) # call the",
"\"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \", country, country,",
"\"\" idfreg = \"\" if 'live_track_id' in contestants: # check if we have",
"if len(devicesid) > 0: devicesid = devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil,",
"urllib.request.urlopen(req) # open the url resource j_obj = json.load(r) # convert to JSON",
"msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build the digital signature # the",
"the contest category = cd['category'] eventname = cd['name'] compid = cd['id'] country =",
"3 chars ID ccc = pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date'] lc",
"the IGC file # see if index day is requestedd # --------------------------------------# #",
"\"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar,",
"regi = \"reg_NOTYET\" if idflarm == '': idflarm = ognid if idflarm !=",
"convert to JSON return j_obj # return the JSON object ################################################################### ######################################################################## def",
"store the IGC file # see if index day is requestedd # --------------------------------------#",
"getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8 in order to avoid problems pname",
"import urllib.request import urllib.error import urllib.parse import hmac import hashlib import base64 import",
"in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry != '': nation",
"that just the FlarmID and OGN tracker pair idflarm = livetrk[0:9] ognpair =",
"build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open",
"ID is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\",
"def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code",
"prt=False): global apiurl global auth date = datetime.now() # get the date hostname",
"print \"CTTCTT\",ctt for contestants in ctt: # print \"FT\", ft, \"\\n\\n\" fname =",
"cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else:",
"# in case of missing FLR/ICA/OGN (deprecated) if idflarm[0] == 'D': idflarm =",
"\"FLR\"+idflarm # assume a Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume",
"nonce = base64.b64encode(os.urandom(36)) # get the once base # build the message message",
"oksta(station): if (station != \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu): if",
"igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\" ognid = \"\"",
"the digital signature # the AUTHORIZATION ID is built now auth = apiurl+rel+'/hmac/v1",
"[] devicesid = \"\" # Build the tracks and turn points, exploring the",
"if 'live_track_id' in contestants: # check if we have the FlarmId from the",
"nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the message digest digest = hmac.new(secretkey, msg=message,",
"prepaeres the infor for the REAL TIME SCORING # # Author: <NAME> -",
"local time # print the time for information only if prt: print(\"Hostname:\", hostname)",
"file # see if index day is requestedd # --------------------------------------# # ===== SETUP",
"secretkey files secpath = cwd+\"/SoaringSpot/\" apiurl = \"http://api.soaringspot.com/\" # soaringspot API URL rel",
"convert the 2 chars ID to the 3 chars ID ccc = pycountry.countries.get(alpha_2=country)",
"url1 = apiurl+rel # get the contest data, first instance cd = gdata(url1,",
"# print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name']",
"ccc = pycountry.countries.get(alpha_2=nation) country3 = ccc.alpha_3 igcid = getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\"",
"format: FLR123456 OGN654321 # case that just the FlarmID and OGN tracker pair",
"= urllib.request.urlopen(req) # open the url resource j_obj = json.load(r) # convert to",
"latitude > flatiu): return (True) else: # southern hemisfere if (latitude > flatil",
"the REAL TIME SCORING # # Author: <NAME> - May 2021 # #import",
"if index day is requestedd # --------------------------------------# # ===== SETUP parameters =======================# #",
"(station != \"FLYMASTER\"): return(True) return(False) ##################### def chkfilati(latitude, flatil, flatiu): if (flatil ==",
"# # Author: <NAME> - May 2021 # #import sys import json import",
"version 1 # ==============================================# utc = datetime.utcnow() # the UTC time date =",
"npil = 0 # init the number of pilots classes = [] pilots",
"cl in getemb(cd, 'classes'): # print \"CLCLCL\", cl classname = cl[\"type\"] # search",
"-*- # This module gets that daya from SoaringSpot and prepaeres the infor",
"# the AUTHORIZATION ID is built now auth = apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\",
"import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl global auth # auth and apiurl",
"name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc",
"in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model' in contestants:",
"print(\"Loc Name:\", lcname, \"Country: \", country, country, \"End date:\", endate) print(\"=========================================\\n\\n\") if prt:",
"ID on the soaringspota regi = \"reg_NOTYET\" if idflarm == '': idflarm =",
"apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ----------",
"defaults for pilots # convert the 2 chars ID to the 3 chars",
"idfreg = \"\" if 'live_track_id' in contestants: # check if we have the",
"is requestedd # --------------------------------------# # ===== SETUP parameters =======================# # where to find",
"urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r",
"flatil or latitude < flatiu): return (True) return(False) ######################################################################## # get the data",
"contestants['live_track_id'] # flarmID and OGN pair if prt: print (\"Live_track:\", livetrk) if len(livetrk)",
"and OGN tracker pair idflarm = livetrk[0:9] ognpair = livetrk[10:] # OGN trackers",
"19: # format: FLR123456 OGN654321 # case that just the FlarmID and OGN",
"= livetrk[10:] # OGN trackers paired if len(idflarm) == 6: # in case",
"req.add_header(\"Content-Type\", \"application/hal+json\") r = urllib.request.urlopen(req) # open the url resource j_obj = json.load(r)",
"apiurl+'rel/' + key) # get the data from the HAL document return cd",
"return (base['_links'][apiurl+'rel/'+ctype]['href']) ################################################################### # # ---------- main code --------------- # # gather the",
"import pycountry from ognddbfuncs import getognreg, getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------#",
"contestants data # print \"CTTCTT\",ctt for contestants in ctt: # print \"FT\", ft,",
"= getemb(contestants, 'pilot')[0]['first_name'] lname = getemb(contestants, 'pilot')[0]['last_name'] # convert it to utf8 in",
"ICAO type else: idflarm = \"OGN\"+idflarm # assume a OGN type # get",
"# convert the 2 chars ID to the 3 chars ID ccc =",
"\"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm, \"idf:\", idfreg,",
"# country code - 2 chars code compcountry = country # contry as",
"the API server req = urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization header",
"Build the tracks and turn points, exploring the contestants and task within each",
"# get the UTC time local_time = datetime.now() # the local time #",
"SoaringSpot livetrk = contestants['live_track_id'] # flarmID and OGN pair if prt: print (\"Live_track:\",",
"< flatil or latitude > flatiu): return (True) else: # southern hemisfere if",
"get the once base # build the message message = nonce+date.encode(encoding='utf-8') + \\",
"req.add_header('Authorization', autho) # build the authorization header req.add_header(\"Accept\", \"application/json\") req.add_header(\"Content-Type\", \"application/hal+json\") r =",
"thru the different classes now within the daya pilots = [] for cl",
"initial base of the tree url1 = apiurl+rel # get the contest data,",
"the data from the soaring spot and return it as a HAL document",
"idflarm = \"FLR\"+idflarm # assume a Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm",
"pname, \"Club:\", club, \"CompID:\", cn, \"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\",",
"club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi, \"Class\": classname, \"IgcID\": igcid,",
"+= 1 pil = {\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\":",
"get the date hostname = socket.gethostname() # directory where to store the IGC",
"OGN DDB ognid = getognflarmid(regi) else: # if we do not have the",
"search for the contestants on each class url3 = getlinks(cl, \"contestants\") ctt =",
"the registration from OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi",
"return(False) ##################### def chkfilati(latitude, flatil, flatiu): if (flatil == 0.0): return (False) if",
"getognflarmid(regi) else: # if we do not have the registration ID on the",
"client.encode(encoding='utf-8') # and the message digest digest = hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature =",
"registration ID on the soaringspota regi = \"reg_NOTYET\" if idflarm == '': idflarm",
"Time is now:\", utc) print(date) # # print the time for information only",
"# --------------------------------------# # ===== SETUP parameters =======================# # where to find the SQLITE3",
"the contestants data # print \"CTTCTT\",ctt for contestants in ctt: # print \"FT\",",
"===== SETUP parameters =======================# # where to find the SQLITE3 database cwd =",
"pycountry.countries.get(alpha_2=country) country = ccc.alpha_3 endate = cd['end_date'] lc = getemb(cd, 'location') # location",
"datetime import datetime import pycountry from ognddbfuncs import getognreg, getognflarmid from simplehal import",
"apiurl global auth # auth and apiurl are globals ######################################################################### def getapidata(url, autho):",
"import os.path from datetime import datetime import pycountry from ognddbfuncs import getognreg, getognflarmid",
"# get the once base nonce = base64.b64encode(os.urandom(36)) # get the once base",
"\"Nation:\", nation, \"Country Code\", country3, \"IGCID:\", igcid, \"Reg:\", regi, \"Model:\", ar, \"Flarm:\", idflarm,",
"9: idflarm = livetrk # case that just the FlarmID, no piaring if",
"\"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll = {\"Class\": classname} classes.append(cll) if",
"is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) # get",
"and OGN pair if prt: print (\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm",
"idflarm = livetrk[0:9] ognpair = livetrk[10:] # OGN trackers paired if len(idflarm) ==",
"getemb(contestants, 'pilot')[0]['igc_id'] idflarm = \"\" ognpair = \"\" ognid = \"\" idfreg =",
"type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a ICAO type else: idflarm",
"gdata(url1, 'contests', prt='no')[0] # get the main data from the contest category =",
"else: # if we do not have the registration ID on the soaringspota",
"print (\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm = livetrk # case that",
"0: devicesid = devicesid[0:-1] if prt: print(\"= Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS",
"the daya pilots = [] for cl in getemb(cd, 'classes'): # print \"CLCLCL\",",
"\"CTTCTT\",ctt for contestants in ctt: # print \"FT\", ft, \"\\n\\n\" fname = getemb(contestants,",
"nation = compcountry else: nation = \"ES\" # by default is SPAIN #",
"assume a OGN type # get the registration from OGN DDB idfreg =",
"0.0): return (False) if (flatil > 0): # northern hemisphere if (latitude <",
"# get the initial base of the tree url1 = apiurl+rel # get",
"get the registration from OGN DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants:",
"= hmac.new(secretkey, msg=message, digestmod=hashlib.sha256).digest() signature = str(base64.b64encode(digest).decode() ) # build the digital signature",
"contestants: regi = contestants['aircraft_registration'] # get the flarm if from the OGN DDB",
"code --------------- # # gather the competition data from SoaringSpot def soa2rts(RTS, client,",
"= \"ICA\"+idflarm # assume a ICAO type else: idflarm = \"OGN\"+idflarm # assume",
"class # search for the contestants on each class url3 = getlinks(cl, \"contestants\")",
"the url resource j_obj = json.load(r) # convert to JSON return j_obj #",
"= apiurl+rel+'/hmac/v1 ClientID=\"'+client+'\",Signature=\"' + \\ signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth)",
"idflarm = \"ICA\"+idflarm # assume a ICAO type else: idflarm = \"OGN\"+idflarm #",
"= \"FLR\"+idflarm # assume a Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm #",
"directory # where to find the clientid and secretkey files secpath = cwd+\"/SoaringSpot/\"",
"the soaring spot and return it as a HAL document def gdata(url, key,",
"the local time # print the time for information only if prt: print(\"Hostname:\",",
"global apiurl j_obj = getapidata(url, auth) # call the fuction that get it",
"globals global apiurl j_obj = getapidata(url, auth) # call the fuction that get",
"contry as defaults for pilots # convert the 2 chars ID to the",
"################################################################### # # ---------- main code --------------- # # gather the competition data",
"######################################################################### def getapidata(url, autho): # get the data from the API server req",
"get the current working directory # where to find the clientid and secretkey",
"idflarm, \"idf:\", idfreg, \"OGNpair\", ognpair, ognid) npil += 1 pil = {\"PilotName\": pname,",
"livetrk) if len(livetrk) == 9: idflarm = livetrk # case that just the",
"data # print \"CTTCTT\",ctt for contestants in ctt: # print \"FT\", ft, \"\\n\\n\"",
"eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname, \"Country: \", country, country, \"End date:\",",
"contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model' in contestants: ar",
"elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a ICAO type else: idflarm =",
"within the daya pilots = [] for cl in getemb(cd, 'classes'): # print",
"else: idflarm = \"OGN\"+idflarm # assume a OGN type # get the registration",
"= fname.encode('utf-8').decode('utf-8') + \\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8')",
"get the once base nonce = base64.b64encode(os.urandom(36)) # get the once base #",
"DDB idfreg = getognreg(idflarm[3:9]) if 'aircraft_registration' in contestants: regi = contestants['aircraft_registration'] # get",
"'yes': # if print is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/'",
"'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club = \"club_NOTYET\" if 'aircraft_model' in",
"contestants['aircraft_registration'] # get the flarm if from the OGN DDB ognid = getognflarmid(regi)",
"base64 import os import socket import os.path from datetime import datetime import pycountry",
"information only if prt: print(\"Hostname:\", hostname) print(\"UTC Time is now:\", utc) print(date) #",
"API server req = urllib.request.Request(url) req.add_header('Authorization', autho) # build the authorization header req.add_header(\"Accept\",",
"once base # build the message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') #",
"else: club = \"club_NOTYET\" if 'aircraft_model' in contestants: ar = contestants['aircraft_model'] else: ar",
"= getemb(cd, 'location') # location data lcname = lc['name'] # location name print(\"\\n\\n=",
"classes = [] pilots = [] devicesid = \"\" # Build the tracks",
"= \"\" idfreg = \"\" if 'live_track_id' in contestants: # check if we",
"\"reg_NOTYET\" if idflarm == '': idflarm = ognid if idflarm != '': devicesid",
"'': idflarm = ognid if idflarm != '': devicesid += idflarm+'/' if prt:",
"instance cd = gdata(url1, 'contests', prt='no')[0] # get the main data from the",
"sys import json import urllib.request import urllib.error import urllib.parse import hmac import hashlib",
"(False) if (flatil > 0): # northern hemisphere if (latitude < flatil or",
"= {\"PilotName\": pname, \"Club\": club, \"CompID\": cn, \"Nation\": nation, \"CountryCode\": country3, \"Registration\": regi,",
"are globals ######################################################################### def getapidata(url, autho): # get the data from the API",
"FLR123456 OGN654321 # case that just the FlarmID and OGN tracker pair idflarm",
"ognddbfuncs import getognreg, getognflarmid from simplehal import HalDocument, Resolver #-------------------------------------------------------------------------------------------------------------------# ######################################################################### global apiurl",
"##################### def chkfilati(latitude, flatil, flatiu): if (flatil == 0.0): return (False) if (flatil",
"from the OGN DDB ognid = getognflarmid(regi) else: # if we do not",
"soaringspota regi = \"reg_NOTYET\" if idflarm == '': idflarm = ognid if idflarm",
"main code --------------- # # gather the competition data from SoaringSpot def soa2rts(RTS,",
"cd['name'] compid = cd['id'] country = cd['country'] # country code - 2 chars",
"that just the FlarmID, no piaring if len(livetrk) == 19: # format: FLR123456",
"if (flatil > 0): # northern hemisphere if (latitude < flatil or latitude",
"from the contest category = cd['category'] eventname = cd['name'] compid = cd['id'] country",
"eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes, \"Pilots\": pilots,",
"= socket.gethostname() # directory where to store the IGC file # see if",
"message message = nonce+date.encode(encoding='utf-8') + \\ client.encode(encoding='utf-8') # and the message digest digest",
"print is required print(json.dumps(j_obj, indent=4)) cd = HalDocument.get_data(HalDocument.from_python( j_obj), apiurl+'rel/' + key) #",
"if (latitude < flatil or latitude > flatiu): return (True) else: # southern",
"import urllib.parse import hmac import hashlib import base64 import os import socket import",
"json.load(r) # convert to JSON return j_obj # return the JSON object ###################################################################",
"southern hemisfere if (latitude > flatil or latitude < flatiu): return (True) return(False)",
"print(\"UTC Time is now:\", utc) print(date) # # print the time for information",
"cd['id'] country = cd['country'] # country code - 2 chars code compcountry =",
"URL rel = \"v1\" # we use API version 1 # ==============================================# utc",
"Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname, \"Comp ID:\", compid) print(\"Loc Name:\", lcname,",
"npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate,",
"TIME SCORING # # Author: <NAME> - May 2021 # #import sys import",
"contestants: cn = contestants['contestant_number'] else: cn = \"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]:",
"SoaringSpot def soa2rts(RTS, client, secretkey, prt=False): global apiurl global auth date = datetime.now()",
"now:\", utc) print(date) # # print the time for information only print(\"Local Time",
"(flatil > 0): # northern hemisphere if (latitude < flatil or latitude >",
"compid = cd['id'] country = cd['country'] # country code - 2 chars code",
"OGN pair if prt: print (\"Live_track:\", livetrk) if len(livetrk) == 9: idflarm =",
"to HAL if prt == 'yes': # if print is required print(json.dumps(j_obj, indent=4))",
"signature+'\",Nonce=\"' + \\ nonce.decode(encoding='utf-8')+'\",Created=\"'+date+'\" ' #print (\"URLiauth:\", auth) # get the initial base",
"\"cn_NOTYET\" if 'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry",
"if 'nationality' in getemb(contestants, 'pilot')[0]: nation = getemb(contestants, 'pilot')[0]['nationality'] else: if compcountry !=",
"= lc['name'] # location name print(\"\\n\\n= Contest ===============================\") print(\"Category:\", category, \"Comp name:\", eventname,",
"default is SPAIN # convert the 2 chars ID to the 3 chars",
"Pilots ===========================\", npil, \"\\n\\n\") print(devicesid) RTS = {\"Compname\": eventname, \"Category\": category, \"Country\": country,",
"\"CLCLCL\", cl classname = cl[\"type\"] # search for each class if prt: print(\"Class:\",",
"# get the data from the soaring spot and return it as a",
"cd def getemb(base, ctype): global apiurl return(base['_embedded'][apiurl+'rel/'+ctype]) def getlinks(base, ctype): global apiurl return",
"pilots = [] devicesid = \"\" # Build the tracks and turn points,",
"\\ \" \"+lname.encode('utf-8').decode('utf-8') if 'club' in contestants: club = contestants['club'].encode('utf-8').decode('utf-8') else: club =",
"urllib.request import urllib.error import urllib.parse import hmac import hashlib import base64 import os",
"that get it # convert to HAL if prt == 'yes': # if",
"else: # southern hemisfere if (latitude > flatil or latitude < flatiu): return",
"== 9: idflarm = livetrk # case that just the FlarmID, no piaring",
"else: ar = \"am_NOTYET\" if 'contestant_number' in contestants: cn = contestants['contestant_number'] else: cn",
"\"Class\": classname, \"IgcID\": igcid, \"AcftModel\": ar, \"Flarmid\": idflarm, \"OGNpair\": ognpair} pilots.append(pil) cll =",
"reference and control if len(devicesid) > 0: devicesid = devicesid[0:-1] if prt: print(\"=",
"1 # ==============================================# utc = datetime.utcnow() # the UTC time date = utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\")",
"(deprecated) if idflarm[0] == 'D': idflarm = \"FLR\"+idflarm # assume a Flarm type",
"apiurl are globals global apiurl j_obj = getapidata(url, auth) # call the fuction",
"# assume a Flarm type elif idflarm[0].isdigit(): idflarm = \"ICA\"+idflarm # assume a",
"regi = contestants['aircraft_registration'] # get the flarm if from the OGN DDB ognid",
"+ key) # get the data from the HAL document return cd def",
"{\"Compname\": eventname, \"Category\": category, \"Country\": country, \"EndDate\": endate, \"Location\": lcname, \"Classes\": classes, \"Pilots\":"
] |
[
"ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature",
"?), desired pressure for properties call fluid = 'Water' t_init = 273.15 pressure",
"it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature)",
"'Water' t_init = 273.15 pressure = 101325 #Check if fluid_type exist and create",
"import * from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import",
"273.15 pressure = 101325 #Check if fluid_type exist and create it if not",
"== None: t = Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type",
"t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature with associated",
"fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature with associated heat capacity and viscosity",
"for properties call fluid = 'Water' t_init = 273.15 pressure = 101325 #Check",
"if asked by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result =",
"TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use and cannot be overwritten\") elif result",
"use and cannot be overwritten\") elif result == TaskDialogResult.No: pass else: break t.Commit()",
"Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing",
"CoolProp to get fluid properties and convert it to internal units if necessary",
"CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double,",
"TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature",
"= TaskDialog.Show(\"Error\", \"Temperature already exist, do you want to overwrite it ?\",TaskDialogCommonButtons.Yes |",
"temperature if asked by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result",
"not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type == None: t = Transaction(doc, \"Create",
"from Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from",
"| TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite",
"Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp shared library",
"#Call CoolProp to get fluid properties and convert it to internal units if",
"t.Start() for i in xrange(1,100): #Call CoolProp to get fluid properties and convert",
"TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use",
"= 101325 #Check if fluid_type exist and create it if not fluid_type =",
"units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p,",
"necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and",
"pressure = 101325 #Check if fluid_type exist and create it if not fluid_type",
"by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature",
"PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial",
"t_init = 273.15 pressure = 101325 #Check if fluid_type exist and create it",
"it if not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type == None: t =",
"fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature with associated heat capacity",
"desired fluid, initial temperature(freezing temperature ?), desired pressure for properties call fluid =",
"#Add new temperature with associated heat capacity and viscosity t = Transaction(doc, \"Add",
"import * from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import",
"type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature with",
"CoolProp shared library and configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\")",
"if fluid_type exist and create it if not fluid_type = FluidType.GetFluidType(doc, fluid) if",
"to get fluid properties and convert it to internal units if necessary temperature",
"uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature ?),",
"== TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in",
"<filename>RevitPyCVC/Fluides/fluide_creer.py from Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import *",
"with associated heat capacity and viscosity t = Transaction(doc, \"Add temperature\") t.Start() for",
"* from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult",
"configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes",
"import * from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import",
"__revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature ?), desired pressure",
"call fluid = 'Water' t_init = 273.15 pressure = 101325 #Check if fluid_type",
"= 'Water' t_init = 273.15 pressure = 101325 #Check if fluid_type exist and",
"PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype =",
"fluid) #Add new temperature with associated heat capacity and viscosity t = Transaction(doc,",
"Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p)",
"get fluid properties and convert it to internal units if necessary temperature =",
"do you want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if",
"FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature with associated heat",
"except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist, do you want to overwrite",
"from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import * from",
"#Check if fluid_type exist and create it if not fluid_type = FluidType.GetFluidType(doc, fluid)",
"= FluidType.GetFluidType(doc, fluid) #Add new temperature with associated heat capacity and viscosity t",
"* from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons",
"* from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import *",
"exist and create it if not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type ==",
"desired pressure for properties call fluid = 'Water' t_init = 273.15 pressure =",
"fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type == None: t = Transaction(doc, \"Create fluid",
"already exist, do you want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel,",
"import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp shared library and",
"Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp shared library and configure PropsSI c_types",
"and viscosity t = Transaction(doc, \"Add temperature\") t.Start() for i in xrange(1,100): #Call",
"Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI",
"TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp shared library and configure",
"fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist, do you want to",
"fluid = 'Water' t_init = 273.15 pressure = 101325 #Check if fluid_type exist",
"viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite temperature",
"units if necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching",
"Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI",
"ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc =",
"= __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature ?), desired",
"TaskDialog.Show(\"Error\", \"Temperature already exist, do you want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No",
"in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist,",
"and trying to overwrite temperature if asked by user in the TaskDialog try:",
"import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import",
"properties call fluid = 'Water' t_init = 273.15 pressure = 101325 #Check if",
"UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite temperature if asked",
"?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density))",
"c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p,",
"to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes:",
"asked by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\",",
"import TaskDialogResult import ctypes #Load CoolProp shared library and configure PropsSI c_types units",
"try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist, do you want",
"and configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI",
"__revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature ?), desired pressure for properties call",
"ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double,",
"temperature\") t.Start() for i in xrange(1,100): #Call CoolProp to get fluid properties and",
"= Transaction(doc, \"Add temperature\") t.Start() for i in xrange(1,100): #Call CoolProp to get",
"\"Temperature already exist, do you want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No |",
"TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\",",
"import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import",
"Transaction(doc, \"Add temperature\") t.Start() for i in xrange(1,100): #Call CoolProp to get fluid",
"from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from",
"TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp",
"\"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new",
"FluidType.GetFluidType(doc, fluid) #Add new temperature with associated heat capacity and viscosity t =",
"fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use and cannot",
"= ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p,",
"doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature ?), desired pressure for",
"density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite temperature if asked by",
"101325 #Check if fluid_type exist and create it if not fluid_type = FluidType.GetFluidType(doc,",
"if not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type == None: t = Transaction(doc,",
"UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite temperature if asked by user in",
"273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite",
"fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature",
"new temperature with associated heat capacity and viscosity t = Transaction(doc, \"Add temperature\")",
"it to internal units if necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density",
"t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add new temperature with associated heat capacity and",
"None: t = Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type =",
"#Set desired fluid, initial temperature(freezing temperature ?), desired pressure for properties call fluid",
"TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist, do you",
"exist, do you want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes)",
"convert it to internal units if necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS)",
"Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes",
"Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions",
"ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid,",
"(x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype",
"= __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing temperature ?), desired pressure for properties",
"= 273.15 pressure = 101325 #Check if fluid_type exist and create it if",
"= (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument",
"ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist, do you want to overwrite it",
"properties and convert it to internal units if necessary temperature = 273.15+i viscosity",
"ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use and cannot be overwritten\") elif",
"CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc",
"from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp shared library and configure PropsSI",
"heat capacity and viscosity t = Transaction(doc, \"Add temperature\") t.Start() for i in",
"i in xrange(1,100): #Call CoolProp to get fluid properties and convert it to",
"internal units if necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER)",
"if necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions",
"temperature(freezing temperature ?), desired pressure for properties call fluid = 'Water' t_init =",
"in use and cannot be overwritten\") elif result == TaskDialogResult.No: pass else: break",
"initial temperature(freezing temperature ?), desired pressure for properties call fluid = 'Water' t_init",
"trying to overwrite temperature if asked by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density))",
"= ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired fluid, initial temperature(freezing",
"if fluid_type == None: t = Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid)",
"user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already",
"PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI = CP.PropsSI PropsSI.argtypes =",
"and convert it to internal units if necessary temperature = 273.15+i viscosity =",
"fluid_type exist and create it if not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type",
"xrange(1,100): #Call CoolProp to get fluid properties and convert it to internal units",
"currently in use and cannot be overwritten\") elif result == TaskDialogResult.No: pass else:",
"shared library and configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI",
"(ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc",
"fluid, initial temperature(freezing temperature ?), desired pressure for properties call fluid = 'Water'",
"Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI",
"result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently",
"fluid properties and convert it to internal units if necessary temperature = 273.15+i",
"to internal units if necessary temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density =",
"import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load",
"library and configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files (x86)\\pythoncvc.net\\RevitPyCVC\\Fluides\\dll\\CoolProp.dll\") PropsSI =",
"\"Add temperature\") t.Start() for i in xrange(1,100): #Call CoolProp to get fluid properties",
"the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: result = TaskDialog.Show(\"Error\", \"Temperature already exist, do",
"pressure for properties call fluid = 'Water' t_init = 273.15 pressure = 101325",
"create it if not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type == None: t",
"= UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite temperature if asked by user",
"result = TaskDialog.Show(\"Error\", \"Temperature already exist, do you want to overwrite it ?\",TaskDialogCommonButtons.Yes",
"= CP.PropsSI PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double",
"* from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import *",
"ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document",
"= Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid)",
"to overwrite temperature if asked by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except",
"= UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to overwrite temperature if",
"= FluidType.GetFluidType(doc, fluid) if fluid_type == None: t = Transaction(doc, \"Create fluid type\")",
"TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException:",
"for i in xrange(1,100): #Call CoolProp to get fluid properties and convert it",
"from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog from",
"temperature = 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying",
"fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use and cannot be",
"in xrange(1,100): #Call CoolProp to get fluid properties and convert it to internal",
"except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use and cannot be overwritten\")",
"#Load CoolProp shared library and configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program Files",
"if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is",
"TaskDialogResult import ctypes #Load CoolProp shared library and configure PropsSI c_types units CP",
"exceptions and trying to overwrite temperature if asked by user in the TaskDialog",
"\"Temperature is currently in use and cannot be overwritten\") elif result == TaskDialogResult.No:",
"try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException: TaskDialog.Show(\"Overwrite error\", \"Temperature is currently in use and",
"fluid_type == None: t = Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit()",
"want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result ==",
"is currently in use and cannot be overwritten\") elif result == TaskDialogResult.No: pass",
"FluidType.GetFluidType(doc, fluid) if fluid_type == None: t = Transaction(doc, \"Create fluid type\") t.Start()",
"PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc =",
"from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import * from",
"error\", \"Temperature is currently in use and cannot be overwritten\") elif result ==",
"from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import",
"ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set desired",
"temperature with associated heat capacity and viscosity t = Transaction(doc, \"Add temperature\") t.Start()",
"Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc, fluid) #Add",
"and create it if not fluid_type = FluidType.GetFluidType(doc, fluid) if fluid_type == None:",
"| TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try: fluid_type.RemoveTemperature(temperature) fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except",
"import ctypes #Load CoolProp shared library and configure PropsSI c_types units CP =",
"capacity and viscosity t = Transaction(doc, \"Add temperature\") t.Start() for i in xrange(1,100):",
"overwrite temperature if asked by user in the TaskDialog try: fluid_type.AddTemperature(FluidTemperature(temperature,viscosity,density)) except ArgumentException:",
"ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p) PropsSI.restype = ctypes.c_double uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document #Set",
"= 273.15+i viscosity = UnitUtils.ConvertToInternalUnits(PropsSI('V','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_PASCAL_SECONDS) density = UnitUtils.ConvertToInternalUnits(PropsSI('D','T',t_init+i,'P',pressure,fluid),DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER) #Catching exceptions and trying to",
"viscosity t = Transaction(doc, \"Add temperature\") t.Start() for i in xrange(1,100): #Call CoolProp",
"ctypes #Load CoolProp shared library and configure PropsSI c_types units CP = ctypes.cdll.LoadLibrary(r\"C:\\Program",
"#Catching exceptions and trying to overwrite temperature if asked by user in the",
"you want to overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result",
"t = Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc, fluid) t.Commit() fluid_type = FluidType.GetFluidType(doc,",
"temperature ?), desired pressure for properties call fluid = 'Water' t_init = 273.15",
"* from Autodesk.Revit.DB.Plumbing import * from Autodesk.Revit.Exceptions import * from Autodesk.Revit.UI import TaskDialog",
"t = Transaction(doc, \"Add temperature\") t.Start() for i in xrange(1,100): #Call CoolProp to",
"associated heat capacity and viscosity t = Transaction(doc, \"Add temperature\") t.Start() for i",
"from Autodesk.Revit.UI import TaskDialogCommonButtons from Autodesk.Revit.UI import TaskDialogResult import ctypes #Load CoolProp shared",
"overwrite it ?\",TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes) if result == TaskDialogResult.Yes: try:",
"fluid) if fluid_type == None: t = Transaction(doc, \"Create fluid type\") t.Start() FluidType.Create(doc,"
] |
[
"d in copy_everything_directories: write_directory(archive, d) for f in wasm_files: archive.write(build_dir / f, arcname=zip_root",
"f) for d in copy_everything_directories: write_directory(archive, d) for f in wasm_files: archive.write(build_dir /",
"Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\")",
"import PurePath, Path import subprocess import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files",
"= [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir =",
"[\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories =",
"\"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\",",
"/ f, arcname=zip_root / f) for d in copy_everything_directories: write_directory(archive, d) for f",
"wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"]",
"for d in copy_everything_directories: write_directory(archive, d) for f in wasm_files: archive.write(build_dir / f,",
"\"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp =",
"build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest =",
"[\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\")",
"archive.write(build_dir / f, arcname=zip_root / wasm_dir / f) print(f\"Successfully built {output_dir / filename}\")",
"root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with",
"mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in root_files: archive.write(root_dir / f, arcname=zip_root",
"\"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode != 0: raise Exception(\"Wasm",
"Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir =",
"open(\"module.json\", \"r\") as file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip'",
"= Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\",",
"= PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir,",
"build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest = json.load(file) zip_root =",
"arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as",
"#!/usr/bin/env python3 import json from pathlib import PurePath, Path import subprocess import tempfile",
"Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir",
"root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\")",
"with open(\"module.json\", \"r\") as file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename =",
"f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if",
"\"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory()",
"subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode != 0:",
"archive: for f in root_files: archive.write(root_dir / f, arcname=zip_root / f) for d",
"in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root /",
"Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename",
"pathlib import PurePath, Path import subprocess import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser()",
"Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest",
"/ d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d /",
"PurePath, Path import subprocess import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files =",
"filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in root_files: archive.write(root_dir / f,",
"\"r\") as file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result",
"/ filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in root_files: archive.write(root_dir /",
"f in root_files: archive.write(root_dir / f, arcname=zip_root / f) for d in copy_everything_directories:",
"result.returncode != 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for",
"for f in wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir / f) print(f\"Successfully",
"manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\",",
"[\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp",
"= Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}')",
"import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files =",
"= tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest = json.load(file)",
"from pathlib import PurePath, Path import subprocess import tempfile import zipfile wasm_pack =",
"= Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir =",
"filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir /",
"Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f in (root_dir /",
"assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED,",
"arcname=zip_root / f) for d in copy_everything_directories: write_directory(archive, d) for f in wasm_files:",
"root_dir / rust_dir]) if result.returncode != 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True)",
"in root_files: archive.write(root_dir / f, arcname=zip_root / f) for d in copy_everything_directories: write_directory(archive,",
"f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in",
"/ rust_dir]) if result.returncode != 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def",
"build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f in (root_dir / d).iterdir():",
"/ d / f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:",
"d) for f in wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir / f)",
"wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir",
"= Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file:",
"f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir",
"tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as file: manifest = json.load(file) zip_root",
"as archive: for f in root_files: archive.write(root_dir / f, arcname=zip_root / f) for",
"import subprocess import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\",",
"d): for f in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file())",
"zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\",",
"= Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir",
"PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir",
"f, arcname=zip_root / f) for d in copy_everything_directories: write_directory(archive, d) for f in",
"build_dir, root_dir / rust_dir]) if result.returncode != 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True,",
"else: assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\",",
"exist_ok=True) def write_directory(archive, d): for f in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive,",
"= json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\",",
"if result.returncode != 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d):",
"result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode",
"if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name) with",
"compresslevel=9) as archive: for f in root_files: archive.write(root_dir / f, arcname=zip_root / f)",
"!= 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f",
"for f in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f,",
"compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in root_files: archive.write(root_dir / f, arcname=zip_root /",
"d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name)",
"0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f in",
"in wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir / f) print(f\"Successfully built {output_dir",
"\"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode != 0: raise",
"d / f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for",
"\"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode != 0: raise Exception(\"Wasm build failed\")",
"rust_dir]) if result.returncode != 0: raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive,",
"tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files",
"def write_directory(archive, d): for f in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f)",
"Path import subprocess import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\",",
"json from pathlib import PurePath, Path import subprocess import tempfile import zipfile wasm_pack",
"\"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\",",
"write_directory(archive, d): for f in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f) else:",
"\"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir",
"copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir =",
"archive.write(root_dir / f, arcname=zip_root / f) for d in copy_everything_directories: write_directory(archive, d) for",
"copy_everything_directories: write_directory(archive, d) for f in wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir",
"subprocess import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\",",
"Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name)",
"as file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result =",
"json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\",",
"file: manifest = json.load(file) zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack,",
"f in wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir / f) print(f\"Successfully built",
"wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir / f) print(f\"Successfully built {output_dir /",
"write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir /",
"wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir",
"= subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode !=",
"in copy_everything_directories: write_directory(archive, d) for f in wasm_files: archive.write(build_dir / f, arcname=zip_root /",
"write_directory(archive, d) for f in wasm_files: archive.write(build_dir / f, arcname=zip_root / wasm_dir /",
"= Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\")",
"zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in root_files: archive.write(root_dir",
"\"web\", \"--out-dir\", build_dir, root_dir / rust_dir]) if result.returncode != 0: raise Exception(\"Wasm build",
"root_files: archive.write(root_dir / f, arcname=zip_root / f) for d in copy_everything_directories: write_directory(archive, d)",
"with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f in root_files:",
"(root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d",
"import tempfile import zipfile wasm_pack = Path(\"~/.cargo/bin/wasm-pack\").expanduser() root_files = [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"]",
"= f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\", build_dir, root_dir / rust_dir])",
"/ f) for d in copy_everything_directories: write_directory(archive, d) for f in wasm_files: archive.write(build_dir",
"f in (root_dir / d).iterdir(): if f.is_dir(): write_directory(archive, f) else: assert(f.is_file()) archive.write(f, arcname=zip_root",
"rust_dir = Path(\"rust\") build_dir_tmp = tempfile.TemporaryDirectory() build_dir = Path(build_dir_tmp.name) with open(\"module.json\", \"r\") as",
"output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f in (root_dir / d).iterdir(): if f.is_dir():",
"python3 import json from pathlib import PurePath, Path import subprocess import tempfile import",
"import json from pathlib import PurePath, Path import subprocess import tempfile import zipfile",
"= [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir = Path(\".\") rust_dir = Path(\"rust\")",
"failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f in (root_dir / d).iterdir(): if",
"\"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"]",
"zip_root = PurePath(f'{manifest[\"name\"]}') filename = f'{manifest[\"name\"]}-{manifest[\"version\"]}.zip' result = subprocess.run([wasm_pack, \"build\", \"--target\", \"web\", \"--out-dir\",",
"f) else: assert(f.is_file()) archive.write(f, arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir / filename,",
"output_dir = Path(\"artifact\") copy_everything_directories = [\"js\", \"lang\", \"templates\"] wasm_dir = Path(\"wasm\") root_dir =",
"/ f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for f",
"archive.write(f, arcname=zip_root / d / f.name) with zipfile.ZipFile(output_dir / filename, mode=\"w\", compression=zipfile.ZIP_DEFLATED, compresslevel=9)",
"= [\"module.json\", \"README.md\", \"CHANGELOG.md\", \"LICENSE\"] wasm_files = [\"gridless_pathfinding_bg.wasm\", \"gridless_pathfinding.js\"] output_dir = Path(\"artifact\") copy_everything_directories",
"raise Exception(\"Wasm build failed\") output_dir.mkdir(parents=True, exist_ok=True) def write_directory(archive, d): for f in (root_dir",
"for f in root_files: archive.write(root_dir / f, arcname=zip_root / f) for d in"
] |
[
"result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result) if root.right:",
"= stack.pop() if not node.left and not node.right and node.val == cur_sum: res.append(lnodes",
"class Solution: def dfs(self, root, cur_sum, lnodes, result): if not root.left and not",
"sum): \"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" result =",
"lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum - node.val, lnodes + [node.val])) return",
"result): if not root.left and not root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes)",
"root, cur_sum, lnodes, result): if not root.left and not root.right and cur_sum ==",
"node.right and node.val == cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum -",
"lnodes, result): if not root.left and not root.right and cur_sum == root.val: lnodes.append(root.val)",
"lnodes + [root.val], result) if root.right: self.dfs(root.right, cur_sum - root.val, lnodes + [root.val],",
"+ [root.val], result) if root.right: self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result)",
"Definition for a binary tree node. # class TreeNode: # def __init__(self, x):",
"root.right: self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result) def pathSum(self, root, sum):",
"root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result)",
"root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val,",
":type sum: int :rtype: List[List[int]] \"\"\" result = [] if not root: return",
"Solution: def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum: int :rtype:",
"class TreeNode: # def __init__(self, x): # self.val = x # self.left =",
"\"\"\" if not root: return [] res = [] stack = [(root, sum,",
"__init__(self, x): # self.val = x # self.left = None # self.right =",
"self.val = x # self.left = None # self.right = None class Solution:",
"= None # self.right = None class Solution: def dfs(self, root, cur_sum, lnodes,",
"self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result) if root.right: self.dfs(root.right, cur_sum -",
"res = [] stack = [(root, sum, [])] while stack: node, cur_sum, lnodes",
"root.left and not root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left,",
"[] res = [] stack = [(root, sum, [])] while stack: node, cur_sum,",
"[] if not root: return result self.dfs(root, sum, [], result) return result #",
"None class Solution: def dfs(self, root, cur_sum, lnodes, result): if not root.left and",
"root: return [] res = [] stack = [(root, sum, [])] while stack:",
"[] stack = [(root, sum, [])] while stack: node, cur_sum, lnodes = stack.pop()",
"sum, [], result) return result # Iterative # Definition for a binary tree",
"if not root: return result self.dfs(root, sum, [], result) return result # Iterative",
"# self.right = None class Solution: def pathSum(self, root, sum): \"\"\" :type root:",
"cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val, lnodes +",
"None # self.right = None class Solution: def dfs(self, root, cur_sum, lnodes, result):",
"cur_sum, lnodes = stack.pop() if not node.left and not node.right and node.val ==",
"= None class Solution: def dfs(self, root, cur_sum, lnodes, result): if not root.left",
"[node.val]) if node.left: stack.append((node.left, cur_sum - node.val, lnodes + [node.val])) if node.right: stack.append((node.right,",
"root.val, lnodes + [root.val], result) def pathSum(self, root, sum): \"\"\" :type root: TreeNode",
"for a binary tree node. # class TreeNode: # def __init__(self, x): #",
":type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" result = [] if",
"result) if root.right: self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result) def pathSum(self,",
"# self.left = None # self.right = None class Solution: def dfs(self, root,",
"cur_sum, lnodes, result): if not root.left and not root.right and cur_sum == root.val:",
"not root.left and not root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left:",
"sum: int :rtype: List[List[int]] \"\"\" if not root: return [] res = []",
"and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val, lnodes",
"= [] stack = [(root, sum, [])] while stack: node, cur_sum, lnodes =",
"# Definition for a binary tree node. # class TreeNode: # def __init__(self,",
"root.val, lnodes + [root.val], result) if root.right: self.dfs(root.right, cur_sum - root.val, lnodes +",
"[root.val], result) if root.right: self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result) def",
"= [(root, sum, [])] while stack: node, cur_sum, lnodes = stack.pop() if not",
"# class TreeNode: # def __init__(self, x): # self.val = x # self.left",
"node.left and not node.right and node.val == cur_sum: res.append(lnodes + [node.val]) if node.left:",
"a binary tree node. # class TreeNode: # def __init__(self, x): # self.val",
"root: return result self.dfs(root, sum, [], result) return result # Iterative # Definition",
"# Iterative # Definition for a binary tree node. # class TreeNode: #",
"[(root, sum, [])] while stack: node, cur_sum, lnodes = stack.pop() if not node.left",
"stack: node, cur_sum, lnodes = stack.pop() if not node.left and not node.right and",
"stack.append((node.left, cur_sum - node.val, lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum - node.val,",
"if not root.left and not root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if",
":type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" if not root: return",
"sum, [])] while stack: node, cur_sum, lnodes = stack.pop() if not node.left and",
"- root.val, lnodes + [root.val], result) def pathSum(self, root, sum): \"\"\" :type root:",
"def dfs(self, root, cur_sum, lnodes, result): if not root.left and not root.right and",
"lnodes + [root.val], result) def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type",
"root, sum): \"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" result",
"List[List[int]] \"\"\" result = [] if not root: return result self.dfs(root, sum, [],",
"self.dfs(root, sum, [], result) return result # Iterative # Definition for a binary",
"- node.val, lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum - node.val, lnodes +",
"node. # class TreeNode: # def __init__(self, x): # self.val = x #",
"if root.left: self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result) if root.right: self.dfs(root.right,",
"result) def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum: int :rtype:",
"None # self.right = None class Solution: def pathSum(self, root, sum): \"\"\" :type",
"not node.left and not node.right and node.val == cur_sum: res.append(lnodes + [node.val]) if",
"= x # self.left = None # self.right = None class Solution: def",
"result) return result # Iterative # Definition for a binary tree node. #",
"node.left: stack.append((node.left, cur_sum - node.val, lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum -",
"self.right = None class Solution: def dfs(self, root, cur_sum, lnodes, result): if not",
"= None # self.right = None class Solution: def pathSum(self, root, sum): \"\"\"",
"TreeNode: # def __init__(self, x): # self.val = x # self.left = None",
"x # self.left = None # self.right = None class Solution: def pathSum(self,",
"Solution: def dfs(self, root, cur_sum, lnodes, result): if not root.left and not root.right",
"TreeNode :type sum: int :rtype: List[List[int]] \"\"\" if not root: return [] res",
":type sum: int :rtype: List[List[int]] \"\"\" if not root: return [] res =",
"and not node.right and node.val == cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left,",
"node.val, lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum - node.val, lnodes + [node.val]))",
"not root: return [] res = [] stack = [(root, sum, [])] while",
"not node.right and node.val == cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum",
"[], result) return result # Iterative # Definition for a binary tree node.",
"not root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum -",
"binary tree node. # class TreeNode: # def __init__(self, x): # self.val =",
"# self.left = None # self.right = None class Solution: def pathSum(self, root,",
"# self.val = x # self.left = None # self.right = None class",
"tree node. # class TreeNode: # def __init__(self, x): # self.val = x",
"[])] while stack: node, cur_sum, lnodes = stack.pop() if not node.left and not",
"\"\"\" result = [] if not root: return result self.dfs(root, sum, [], result)",
"# def __init__(self, x): # self.val = x # self.left = None #",
"self.right = None class Solution: def pathSum(self, root, sum): \"\"\" :type root: TreeNode",
"not root: return result self.dfs(root, sum, [], result) return result # Iterative #",
"class Solution: def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum: int",
"root, sum): \"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" if",
"dfs(self, root, cur_sum, lnodes, result): if not root.left and not root.right and cur_sum",
"and node.val == cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum - node.val,",
"root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" if not root: return []",
"= [] if not root: return result self.dfs(root, sum, [], result) return result",
"root.left: self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result) if root.right: self.dfs(root.right, cur_sum",
"self.left = None # self.right = None class Solution: def dfs(self, root, cur_sum,",
"result self.dfs(root, sum, [], result) return result # Iterative # Definition for a",
"- root.val, lnodes + [root.val], result) if root.right: self.dfs(root.right, cur_sum - root.val, lnodes",
"node, cur_sum, lnodes = stack.pop() if not node.left and not node.right and node.val",
"List[List[int]] \"\"\" if not root: return [] res = [] stack = [(root,",
"root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" result = [] if not",
"TreeNode :type sum: int :rtype: List[List[int]] \"\"\" result = [] if not root:",
"sum): \"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" if not",
"x # self.left = None # self.right = None class Solution: def dfs(self,",
"node.val == cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum - node.val, lnodes",
"# self.right = None class Solution: def dfs(self, root, cur_sum, lnodes, result): if",
"+ [node.val])) if node.right: stack.append((node.right, cur_sum - node.val, lnodes + [node.val])) return res",
"if root.right: self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result) def pathSum(self, root,",
"res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum - node.val, lnodes + [node.val])) if",
"def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]]",
"self.left = None # self.right = None class Solution: def pathSum(self, root, sum):",
"and not root.right and cur_sum == root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum",
"pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\"",
"if not node.left and not node.right and node.val == cur_sum: res.append(lnodes + [node.val])",
"stack = [(root, sum, [])] while stack: node, cur_sum, lnodes = stack.pop() if",
"== cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum - node.val, lnodes +",
"== root.val: lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val, lnodes + [root.val],",
"return result self.dfs(root, sum, [], result) return result # Iterative # Definition for",
"x): # self.val = x # self.left = None # self.right = None",
"if not root: return [] res = [] stack = [(root, sum, [])]",
"self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result) def pathSum(self, root, sum): \"\"\"",
"[root.val], result) def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum: int",
"result = [] if not root: return result self.dfs(root, sum, [], result) return",
":rtype: List[List[int]] \"\"\" if not root: return [] res = [] stack =",
"stack.pop() if not node.left and not node.right and node.val == cur_sum: res.append(lnodes +",
"+ [root.val], result) def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum:",
":rtype: List[List[int]] \"\"\" result = [] if not root: return result self.dfs(root, sum,",
"\"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" if not root:",
"return result # Iterative # Definition for a binary tree node. # class",
"while stack: node, cur_sum, lnodes = stack.pop() if not node.left and not node.right",
"None class Solution: def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type sum:",
"cur_sum - root.val, lnodes + [root.val], result) if root.right: self.dfs(root.right, cur_sum - root.val,",
"cur_sum: res.append(lnodes + [node.val]) if node.left: stack.append((node.left, cur_sum - node.val, lnodes + [node.val]))",
"Iterative # Definition for a binary tree node. # class TreeNode: # def",
"lnodes.append(root.val) result.append(lnodes) if root.left: self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result) if",
"def __init__(self, x): # self.val = x # self.left = None # self.right",
"cur_sum - node.val, lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum - node.val, lnodes",
"lnodes = stack.pop() if not node.left and not node.right and node.val == cur_sum:",
"result # Iterative # Definition for a binary tree node. # class TreeNode:",
"\"\"\" :type root: TreeNode :type sum: int :rtype: List[List[int]] \"\"\" result = []",
"int :rtype: List[List[int]] \"\"\" result = [] if not root: return result self.dfs(root,",
"cur_sum - root.val, lnodes + [root.val], result) def pathSum(self, root, sum): \"\"\" :type",
"= None class Solution: def pathSum(self, root, sum): \"\"\" :type root: TreeNode :type",
"return [] res = [] stack = [(root, sum, [])] while stack: node,",
"+ [node.val]) if node.left: stack.append((node.left, cur_sum - node.val, lnodes + [node.val])) if node.right:",
"int :rtype: List[List[int]] \"\"\" if not root: return [] res = [] stack",
"sum: int :rtype: List[List[int]] \"\"\" result = [] if not root: return result",
"if node.left: stack.append((node.left, cur_sum - node.val, lnodes + [node.val])) if node.right: stack.append((node.right, cur_sum"
] |
[
"def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and returns a decrypted one\"\"\" cipher",
"\"\"\"Reads an an obfuscated object from a file\"\"\" file = open(path, \"rb\") obj",
"returns an encrypted bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj):",
"Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string and returns an encrypted",
"an encrypted bytes object and returns a decrypted one\"\"\" cipher = Fernet(key) return",
"= Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string and returns an",
"encode(obj): \"\"\"Encodes an object as a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a",
"as a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into an object\"\"\"",
"def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a file and obfuscates\"\"\" obj =",
"cryptography.fernet import Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an",
"\"utf8\")) def encode(obj): \"\"\"Encodes an object as a string\"\"\" return jsonpickle.encode(obj) def decode(obj):",
"= Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object as a string\"\"\"",
"an object as a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into",
"cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string and returns",
"= encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an",
"encode(obj) obj = encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads",
"decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from a file\"\"\" file = open(path, \"rb\")",
"b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and returns",
"object to a file and obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj) file",
"path): \"\"\"Writes an object to a file and obfuscates\"\"\" obj = encode(obj) obj",
"def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from a file\"\"\" file = open(path,",
"obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close()",
"= base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and returns a decrypted",
"def decode(obj): \"\"\"Decodes a string into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path):",
"import base64 import jsonpickle from cryptography.fernet import Fernet key = b'\\<KEY>' key =",
"encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a file and obfuscates\"\"\" obj = encode(obj)",
"Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object as a string\"\"\" return",
"into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a",
"<reponame>VergilTheHuragok/SciFi_Text_Adventure_Python import base64 import jsonpickle from cryptography.fernet import Fernet key = b'\\<KEY>' key",
"\"\"\"Writes an object to a file and obfuscates\"\"\" obj = encode(obj) obj =",
"object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a file and",
"an obfuscated object from a file\"\"\" file = open(path, \"rb\") obj = file.read()",
"key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object",
"from a file\"\"\" file = open(path, \"rb\") obj = file.read() file.close() obj =",
"return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into an object\"\"\" return jsonpickle.decode(obj) def",
"key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and returns a",
"file and obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj) file = open(path, \"wb\")",
"jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a file and obfuscates\"\"\" obj",
"jsonpickle from cryptography.fernet import Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message):",
"and returns a decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes",
"returns a decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a",
"a decrypted string and returns an encrypted bytes object\"\"\" cipher = Fernet(key) return",
"and obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj) file = open(path, \"wb\") file.write(obj)",
"file = open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object",
"bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object",
"base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and returns a decrypted one\"\"\"",
"obj = encode(obj) obj = encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close() def",
"an an obfuscated object from a file\"\"\" file = open(path, \"rb\") obj =",
"import Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted",
"a decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted",
"\"\"\"Takes an encrypted bytes object and returns a decrypted one\"\"\" cipher = Fernet(key)",
"and returns an encrypted bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def",
"jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj,",
"file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from a file\"\"\" file",
"return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a file and obfuscates\"\"\"",
"\"\"\"Takes a decrypted string and returns an encrypted bytes object\"\"\" cipher = Fernet(key)",
"decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and returns a decrypted one\"\"\" cipher =",
"return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string and returns an encrypted bytes",
"def encode(obj): \"\"\"Encodes an object as a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes",
"encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated",
"file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from a file\"\"\" file =",
"file = open(path, \"rb\") obj = file.read() file.close() obj = decrypt(obj) obj =",
"= b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes object and",
"a file and obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj) file = open(path,",
"import jsonpickle from cryptography.fernet import Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def",
"open(path, \"rb\") obj = file.read() file.close() obj = decrypt(obj) obj = decode(obj) return",
"file\"\"\" file = open(path, \"rb\") obj = file.read() file.close() obj = decrypt(obj) obj",
"string into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to",
"encrypted bytes object and returns a decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message)",
"Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes an encrypted bytes",
"a string into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object",
"object and returns a decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message):",
"object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object as",
"decode(obj): \"\"\"Decodes a string into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes",
"\"rb\") obj = file.read() file.close() obj = decrypt(obj) obj = decode(obj) return obj",
"obfuscated object from a file\"\"\" file = open(path, \"rb\") obj = file.read() file.close()",
"\"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from a file\"\"\"",
"encrypt(message): \"\"\"Takes a decrypted string and returns an encrypted bytes object\"\"\" cipher =",
"string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into an object\"\"\" return jsonpickle.decode(obj)",
"object from a file\"\"\" file = open(path, \"rb\") obj = file.read() file.close() obj",
"a file\"\"\" file = open(path, \"rb\") obj = file.read() file.close() obj = decrypt(obj)",
"from cryptography.fernet import Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key) def decrypt(bytes_message): \"\"\"Takes",
"= open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from",
"an object to a file and obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj)",
"open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an an obfuscated object from a",
"string and returns an encrypted bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\"))",
"= open(path, \"rb\") obj = file.read() file.close() obj = decrypt(obj) obj = decode(obj)",
"decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string",
"a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into an object\"\"\" return",
"\"\"\"Encodes an object as a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string",
"obj = encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path): \"\"\"Reads an",
"decrypted string and returns an encrypted bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message,",
"encrypted bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an",
"\"\"\"Decodes a string into an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an",
"to a file and obfuscates\"\"\" obj = encode(obj) obj = encrypt(obj) file =",
"= encode(obj) obj = encrypt(obj) file = open(path, \"wb\") file.write(obj) file.close() def decrypt_obj_from_file(path):",
"bytes object and returns a decrypted one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def",
"one\"\"\" cipher = Fernet(key) return cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string and",
"return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object as a string\"\"\" return jsonpickle.encode(obj)",
"def encrypt(message): \"\"\"Takes a decrypted string and returns an encrypted bytes object\"\"\" cipher",
"cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object as a string\"\"\" return jsonpickle.encode(obj) def",
"an object\"\"\" return jsonpickle.decode(obj) def encrypt_obj_to_file(obj, path): \"\"\"Writes an object to a file",
"cipher.decrypt(bytes_message) def encrypt(message): \"\"\"Takes a decrypted string and returns an encrypted bytes object\"\"\"",
"an encrypted bytes object\"\"\" cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes",
"base64 import jsonpickle from cryptography.fernet import Fernet key = b'\\<KEY>' key = base64.urlsafe_b64encode(key)",
"cipher = Fernet(key) return cipher.encrypt(bytes(message, \"utf8\")) def encode(obj): \"\"\"Encodes an object as a",
"object as a string\"\"\" return jsonpickle.encode(obj) def decode(obj): \"\"\"Decodes a string into an"
] |